关于 UITableView 的 willDisplayCell

willDisplayCellUITableView 的一个代理方法,自定义显示的方法一共有如上几个。说到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 画个分割线上去了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章