[iOS] UITableViewDelegate方法的筆記(willDisplayCell)

之前看各種範例的時候,常會發現UITableView實作了某個特殊的delegate方法:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

對於這個方法,我最初看到有人拿來做出cell的特效,比方說在顯示前讓cell比較淡,或是略為旋轉,然後才轉正的動畫。

但也有人拿來設定cell內的views,反之,在原本大家都拿來設定views的delegate方法內,他僅僅只是回傳cell,這令我不得其解。

不過在官方的文件內,他是這樣說這個方法的:
A table view sends a tableView:willDisplayCell:forRowAtIndexPath: message to its delegate just before it draws a row. If the delegate chooses to implement this method, it can make last-minute changes to the cell object before it is displayed. With this method, the delegate should change only state-based properties that were set earlier by the table view, such as selection and background color, and not content.
換言之,他適合拿來設定負擔較輕的特性,比方說selection、背景顏色,而不是內容,比方說創立新的views放進去,或是設定views的特性,比方說標題的文字、圖片之類的。

實際使用時,如果你在這邊才去設定文字或是圖片,會有閃爍的感覺,然後你上下捲動他又會呼叫到這個方法去設定cell,對於使用者來說可能不是很舒服。

留言