关于tableview cell之间分割线

本文探讨了如何在UITableView中实现只在有数据的Cell下方显示分割线,并确保分割线紧贴左侧,避免间隙。介绍了两种方法,包括默认设置调整和自定义Cell的解决方案,同时提到了在实现过程中遇到的一个小错误。

这里写图片描述

我们都知道 默认显示的tableview 分割线是全部显示的
如果想要不显示 很简单
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

但是如何只让有数据的显示 并且分割线最左边不留间隙呢
有如下两个方法

方法一:

//使有数据的cell 显示下划线
self.tableView.tableFooterView = [[UIView alloc]init];
//设置分割线内边距
self.tableView.separatorInset = UIEdgeInsetsZero;

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    //iOS8以后  需要设置layoutMargins 
    self.tableView.layoutMargins = UIEdgeInsetsZero;
}
//cell也需要设置
cell.layoutMargins = UIEdgeInsetsZero;

方法二: 自定义cell


// .m自定义UIView属性
@property(nonatomic,strong)UIView *separatorView;
//懒加载创建
-(UIView *)separatorView{

    if (_separatorView == nil) {

        _separatorView = [[UIView alloc]init];
        _separatorView.backgroundColor = [UIColor blackColor];
        _separatorView.alpha = 0.6;
    }
    return _separatorView;
}
//在这个方法中添加
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self.contentView addSubview:_separatorView];
    }
    return self;
}
//在layout方法里设置frame
-(void)layoutSubviews{
    [super layoutSubviews];
    CGFloat w = self.bounds.size.width;
    CGFloat h = 1;
    CGFloat x = 0;
    CGFloat y = self.bounds.size.height-h;
    self.separatorView.frame = CGRectMake(x, y, w, h);
}

tip : 这里遇到个傻傻小BUG

//在使用懒加载时 带下划线的成员变量并不会触发get方法
 [self.contentView addSubview:_separatorView];
 //应该改为
  [self.contentView addSubview:self.separatorView];

 ps:因为之前都不适用懒加载 直接在init方法里创建了  导致使用下划线 习惯了  ...找了半天 好傻
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值