簡體   English   中英

UITableView willDisplayCell 方法的錯誤行為

[英]Misbehavior of UITableView willDisplayCell method

有一個UITableView的帖子。
看到的帖子 ID 保存在 sqlite 中
我想顯示,看到的帖子是橙色的,其他帖子是黑色的。
但是當我在willDisplayCell方法中為看到的帖子設置橙色時,一些單元格的顏色不正確,否則打印日志(“着色”)是正確的。

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let post = postDataSource.posts[indexPath.row]
    print(post.id)
    let cellPost = cell as? PostListViewCell

    if post.isRead.boolValue == true {
        print("Color it")
        cellPost!.body.textColor = UIColor.orangeColor()
        cellPost!.title.textColor = UIColor.orangeColor()
    }
}

例如,如果只看到一個帖子,“Color it”就會打印一次。 這是正確的。 但是其他一些單元格是橙色的,沒有“着色”日志。

嘗試完成 if 語句

 if (post.isRead.boolValue == true) {
    print("Color it")
    cellPost!.body.textColor = UIColor.orangeColor()
    cellPost!.title.textColor = UIColor.orangeColor()
}else{
    cellPost!.body.textColor = UIColor.blackColor()
    cellPost!.title.textColor = UIColor.blackColor()}

1.Reusable table-view cell對象的理解

來自蘋果文檔

出於性能原因,表視圖的數據源通常應在其tableView(_:cellForRowAt:)方法中將單元格分配給行時重用UITableViewCell對象。 表視圖維護數據源已標記為重用的 UITableViewCell 對象的隊列或列表。 當要求為表格視圖提供新單元格時,從數據源對象調用此方法。

如果現有單元格可用,則此方法使現有單元格出列,或者使用您之前注冊的類或 nib 文件創建一個新單元格。

如果沒有可重用的單元格並且您沒有注冊類或 nib 文件,則此方法返回 nil。

2.prepareForReuse()的使用

來自蘋果文檔

如果 UITableViewCell 對象是可重用的——也就是說,它有一個重用標識符——這個方法會在對象從 UITableView 方法dequeueReusableCell(withIdentifier:)返回之前調用。 出於性能原因,

您應該只重置與內容無關的單元格屬性,例如 alpha、編輯和選擇狀態。

tableView(_:cellForRowAt:) 中表格視圖的委托在重用單元格時應始終重置所有內容。 如果單元格對象沒有關聯的重用標識符,則不會調用此方法。 如果覆蓋此方法,則必須確保調用超類實現。

另一種手動重置@RJiryes 已經描述的單元格屬性的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM