【问题标题】:Misbehavior of UITableView willDisplayCell methodUITableView willDisplayCell 方法的不当行为
【发布时间】:2017-06-13 11:14:01
【问题描述】:

有一个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”日志的情况下被染成橙色。

【问题讨论】:

  • 关于为什么不使用 CellForRowAtIndexPath 设置单元格样式的任何具体原因?
  • 使用自定义单元格
  • @SandeepBhandari 我在 DataSource 中使用了 CellForRowAtIndexPath,我不想在 DataSource 中设置样式
  • 然后在您的单元子类中创建名为 configCell 的函数,并在 cellForRowAtIndexPath 中调用 configCell。这更干净,因为单元负责设置自己的样式:)

标签: ios swift uitableview


【解决方案1】:

尝试完成 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()}

【讨论】:

  • 谢谢。我不想这样做。我知道它可以解决问题,但为什么我需要在默认颜色为黑色时再次染成黑色
【解决方案2】:

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

来自Apple Documentation

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

如果一个现有的单元格可用,则此方法使现有单元格出列或创建 使用您之前注册的类或 nib 文件创建一个新文件。

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

2.prepareForReuse()的使用

来自Apple Documentation

如果 UITableViewCell 对象是可重用的——也就是说,它有一个重用标识符——这个方法在对象从 UITableView 方法返回之前被调用 dequeueReusableCell(withIdentifier:) .出于性能原因,

您应该只重置与不相关的单元格的属性 内容,例如 alpha、编辑和选择状态。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    相关资源
    最近更新 更多