iOS 管理separator的UITableViewCell子类

@interface ZDBaseTableViewCell : UITableViewCell

@property (nonatomic, assign) BOOL showsSeparator;// default is YES
@property (nonatomic, assign) CGFloat separatorLeading;// default is 15.f

@end
@interface ZDBaseTableViewCell ()

@property (nonatomic, strong) CALayer *separatorLayer;

@end

@implementation ZDBaseTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    // 默认15
    _separatorLeading = 15.f;
    _showsSeparator = YES;
    
    // 设置选中颜色
//    self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.bounds];
//    self.selectedBackgroundView.backgroundColor = [UIColor zd_separatorColor];
    
    // 设置分隔线
    _separatorLayer = [[CALayer alloc] init];
    _separatorLayer.backgroundColor = [UIColor zd_separatorColor].CGColor;
    [self.layer addSublayer:_separatorLayer];
}

- (void)setShowsSeparator:(BOOL)showsSeparator {
    _showsSeparator = showsSeparator;
    _separatorLayer.hidden = !showsSeparator;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (_showsSeparator) {
        [UIView setAnimationsEnabled:NO];
        self.separatorLayer.frame = CGRectMake(_separatorLeading, CGRectGetHeight(self.bounds) - SINGLE_LINE_ADJUST_OFFSET, CGRectGetWidth(self.bounds) - _separatorLeading, SINGLE_LINE_HEIGHT);
        [UIView setAnimationsEnabled:YES];
    }
}

@end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容