【问题标题】:First and Last Cell Change Color When Scrolling in UITableView在 UITableView 中滚动时第一个和最后一个单元格更改颜色
【发布时间】:2019-12-21 00:53:57
【问题描述】:

我有一个具有特定颜色的自定义单元格列表,这些颜色取决于时间。计时器运行以使每个单元格的颜色保持最新。每次我一直滚动到 tableView 的顶部或底部时,tableView 中的第一个和最后一个单元格都有彼此的颜色。例如,如果第一个单元格为绿色,最后一个单元格为红色,则当我向上滚动时第一个单元格变为红色并在一秒钟后变为绿色。这是我的计时器:

// Refreshes the labels every second to update the time
    timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { [weak self] _ in
        if let s = self, let tableView = s.tableView, let indexPaths = tableView.indexPathsForVisibleRows {
            for indexPath in indexPaths {
                guard let cell = tableView.cellForRow(at: indexPath) as? PersonCell else { return }
                let person = s.people[indexPath.section]
                let day = dayOfWeekIn(timeZone: person.timeZone)

                // update text of cell and check some conditions to set the gradient of the cell accordingly
        }
    })

我也在cellForRowAt中配置了我的单元格,但是这些配置与单元格的背景无关,所以我认为不是问题的原因。如果有人能帮我解决这个问题,我将不胜感激。

【问题讨论】:

  • 单元格被重复使用...这意味着,当您向下滚动然后向上滚动时,您可以得到一个单元格,它的背景颜色在它位于第 20 行时变为红色,但是now 用于第 0 行。您需要在cellForRowAt 每次中明确设置所需的背景颜色。
  • @DonMag 作为答案,你是绝对正确的。

标签: ios swift uitableview nstimer cagradientlayer


【解决方案1】:

细胞被重复使用...

这意味着,当您向下滚动然后再向上滚动时,您可以看到一个单元格的背景颜色更改为红色,而它位于第 20 行,但现在用于第 0 行。

您需要在cellForRowAt 中明确设置所需的背景颜色每次

编辑

您可以使用当前更改背景颜色的方法,但您必须将当前背景颜色作为数据源的一部分进行跟踪。

例如,将currentBackgroundColor 属性添加到您的Person 类。当你这样做时:

// update text of cell and check some conditions to set the gradient of the cell accordingly

你也会做(类似的事情):

data[indexPath.section].currentBackgroundColor = UIColor.green

当你接到cellForRowAt 的电话时,你会这样做:

cell.backgroundColor = data[indexPath.section].currentBackgroundColor

没有看到你的实际数据源/结构,很难给你一个明确的例子,但就是这样。

【讨论】:

  • 我明白了。那么我是否必须每秒重新加载 tableView 才能改变颜色?
  • 不...请参阅我的答案中的编辑。
猜你喜欢
  • 2012-02-22
  • 2012-10-22
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
相关资源
最近更新 更多