關於 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 畫個分割線上去了。

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