实现tableViewCell分割线(全屏)

代码下载地址

iOS7后分割线默认左边是有15个像素的边距


实现tableViewCell分割线(全屏)_第1张图片
分割线默认
1. 设置边距 点击这篇文章tableView分割线设置全屏
2. 自定义分割线
  • 首先隐藏系统分割线self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  • 在cell上添加替换分割线控件

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[TestTableViewCell identifier]];
    if (cell == nil) {
        cell = [[TestTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[TestTableViewCell identifier]];
        cell.indexPathType = indexPath;
    }
    
    return cell;
}

#import 

@interface TestTableViewCell : UITableViewCell

@property (nonatomic ,strong) UILabel *lineLabel;
@property (nonatomic ,strong) NSIndexPath *indexPathType;
+ (NSString *)identifier;

@end

#import "TestTableViewCell.h"

@implementation TestTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self lineLabel];
    }
    return self;
}
- (void)setIndexPathType:(NSIndexPath *)indexPathType{
    _indexPathType = indexPathType;
    if (indexPathType.row == 0) {
        _lineLabel.hidden = YES;
    }
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
- (UILabel *)lineLabel{
    if (!_lineLabel) {
        _lineLabel = [UILabel new];
        _lineLabel.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1);
        _lineLabel.backgroundColor = [UIColor redColor];
        [self.contentView addSubview:_lineLabel];
    }
    return _lineLabel;
}
+ (NSString *)identifier{
    return NSStringFromClass([self class]);
}

@end

实现tableViewCell分割线(全屏)_第2张图片
自定义分割线
3. 重写cell的setFrame方法

原理是重写cell的setFrame方法把cell的高度减少,露出tableView的背景色。重写过这个方法后就不需要考虑适配等问题,前提把分割线隐藏。

  • 隐藏分割线
_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

  • 给tableView设置背景色
_tableView.backgroundColor = [UIColor yellowColor];
  • 重写setFrame方法
- (void) setFrame:(CGRect)frame{
    frame.size.height -= 0.8;
    [super setFrame:frame];
}
实现tableViewCell分割线(全屏)_第3张图片
重写setFrame方法
4. 重写cell的drawRect方法
// 自绘分割线
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillRect(context, rect);

    CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
    CGContextStrokeRect(context, CGRectMake(0, rect.size.height - 1, rect.size.width, 1));
}
实现tableViewCell分割线(全屏)_第4张图片
重写cell的drawRect方法

你可能感兴趣的:(实现tableViewCell分割线(全屏))