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