实现tableViewCell分割线(全屏)

代码下载地址

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


分割线默认
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 <UIKit/UIKit.h>

@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

自定义分割线
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];
}
重写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));
}
重写cell的drawRect方法
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容