我们都知道 默认显示的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方法里创建了 导致使用下划线 习惯了 ...找了半天 好傻
本文探讨了如何在UITableView中实现只在有数据的Cell下方显示分割线,并确保分割线紧贴左侧,避免间隙。介绍了两种方法,包括默认设置调整和自定义Cell的解决方案,同时提到了在实现过程中遇到的一个小错误。
1145

被折叠的 条评论
为什么被折叠?



