willDisplayCell
是 UITableView
的一个代理方法,自定义显示的方法一共有如上几个。说到willDisplayCell
,很多人会把它和cellForRowAtIndexPath
做对比。
通过打断点发现,tableview
中先走cellForRowAtIndexPath
方法,然后再走willDisplayCell
方法。网上很多人建议,对于数据绑定填充放到willDisplayCell
中执行。但是通过试验,一般情况下,在cellForRowAtIndexPath
中进行数据绑定填充,并不会造成卡顿和过度消耗性能的情况。特别复杂的 cell 除外。
willDisplayCell
平时用的最多的是自定义 UITableView
分割线。系统默认情况下,UITableView
的分割线左边是没有置顶的。打印它的 inset
可以得到值为 {0, 15, 0, 0}
NSLog(@"%@", NSStringFromUIEdgeInsets(tableView.separatorInset));
如果想要分割线左右两边都顶格,有两个方法。
- (void)viewDidLayoutSubviews {
if ([_tableView respondsToSelector: @selector(setSeparatorInset:)]) {
[_tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([_tableView respondsToSelector: @selector(setLayoutMargins:)]) {
[_tableView setLayoutMargins:UIEdgeInsetsZero];
}
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
方法一只能修改整体分割线,如果要针对不同的 cell 设置不同的分割线,方法二比较适用。以后面对各种 cell 都不需要在自定义时再去拖个 view 画个分割线上去了。