要自定义tableview的分割线,需要手写代码往UItableviewCell 的contentView中添加视图,控制好添加视图的高度和宽度就可以实现。
效果图:
第一步:设置cell,设置的方式有xib,tableview动态原型方式,还有就是手写代码方式,在这使用动态原型,参考cell的创建方式随笔.
自定义cell类:
@interface HJTableViewCell : UITableViewCell
@property (nonatomic,strong) HJContact *contact;
+ (instancetype)tableViewCell:(UITableView *)tableView;
@end
@interface HJTableViewCell()
// 表格分割线视图
@property (nonatomic,weak) UIView *separatorView;
@end
@implementation HJTableViewCell
+ (instancetype)tableViewCell:(UITableView *)tableView{
#warning 先从换成池中取,如果缓存池中没有可循环利用的cell,先去storyboard中找合适的cell ,cell是从storyboard中创建出来的,而不是手写代码方式alloc出来的
// 此标识要和storyboard 本控制器中的动态cell设置的identify标识一致
static NSString *ID = @"contactCell";
return [tableView dequeueReusableCellWithIdentifier:ID];
}
/**
* 如果cell是通过storyboard或者xib创建的,就不可能会调用这个方法来初始化cell
* 如果cell是通过手写代码创建,才会调用这个方法来初始化cell
*/
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
}
return self;
}
/**
* 如果cell是通过storyboard或者xib创建的,就会调用这个方法来初始化cell
* 这个方法的作用类似于init方法
*/
- (void)awakeFromNib {
NSLog(@"%s",__func__);
// Initialization code
// 自定义表格分割线
UIView *separatorView = [[UIView alloc] init];
#warning 添加至cell的内容视图中
[self.contentView addSubview:separatorView];
self.separatorView = separatorView;
separatorView.alpha = 0.5;
separatorView.backgroundColor = [UIColor redColor];
}
/**
* 在这个方法中设置子控件的frame
* 在此方法中进行设置frame 因为在此方法中获取到得self.frame才是最准确的,因为tableView可能
* 设置了行高等等 etc...
*
*/
- (void)layoutSubviews{
NSLog(@"%s",__func__);
#warning 一定得调用父类的方法
[super layoutSubviews];
CGFloat x = 10;
CGFloat y = self.frame.size.height - 1;
CGFloat w = self.frame.size.width-20;
CGFloat h = 1;
self.separatorView.frame = CGRectMake(x, y, w, h);
}
- (void)setContact:(HJContact *)contact{
self.textLabel.text = contact.name;
#warning 详情默认会显示不了,需要去storyboard动态单元格中设置 style为right Detail
self.detailTextLabel.text = contact.tel;
}
修改tableview默认分割线为none
// 此方法是在本控制器loadView方法初始化view完毕后系统调用此方法
- (void)viewDidLoad {
[super viewDidLoad];
// 设置表格分割线样式
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
#warning 添加至cell的内容视图中
[self.contentView addSubview:separatorView];不然事情就白做了
cell创建使用:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
HJTableViewCell *cell = [HJTableViewCell tableViewCell:tableView];
cell.contact = self.contactList[indexPath.row];
return cell;
}
完成以上步骤后自定义cell分割线完毕.