UITableView 将显示单元格方法的不当行为



有一UITableView帖子。
看到的帖子 id 保存在我要显示的 sqlite
中,看到的帖子以橙色保存,其他帖子以黑色保存。
但是当我willDisplayCell方法中为看到的帖子设置橙色时,某些单元格的橙色颜色不正确,否则打印日志("Color it")是正确的。

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"就会打印一次。 这是正确的。但是其他一些单元格是橙色的,没有"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.理解可重用的表视图单元格对象

来自苹果文档

出于性能原因,表视图的数据源通常应重用UITableViewCell对象,当它为其中的行分配单元格时tableView(_:cellForRowAt:)方法.表视图维护队列或列表 UITableViewCell 数据源已标记为重用的对象。当要求为表视图提供新单元格时,从数据源对象调用此方法。

此方法将现有单元格(如果可用)取消排队或创建 使用您之前注册的类或 NIB 文件的新文件。

如果没有单元格可供重用,并且您没有注册类或 nib 文件,则此方法返回 nil。

2.准备重用()的使用

来自苹果文档

如果 UITableViewCell 对象是可重用的(即,它具有重用标识符),则在从 UITableView 方法返回对象之前调用此方法dequeueReuseableCell(withIdentifier:).出于性能原因,

您应该只重置与 内容,例如 Alpha、编辑和选择状态。

表视图的委托tableView(_:cellForRowAt:)在重用单元格时应始终重置所有内容。如果单元格对象没有关联的重用标识符,则不调用此方法。如果重写此方法,则必须确保调用超类实现。

手动重置@RJiryes已经描述的单元格属性的另一种方法。

最新更新