如何设置特定UITableViewCell的背景颜色

问题描述 投票:0回答:1

我有一个动态的tableview。它提供了整整一个月的具体信息。每天都有自己的细胞。并且目标是设置与今天具有相同日期的单元格的背景颜色。

第一。我在cellForRow indexPath中设置每个单元格的标签:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MonthlyCell", for: indexPath)

        guard let monthlyCell = cell as? MonthlyTableViewCell else {
            fatalError("Designated cell couldn't found")
        }

        monthlyCell.tag = indexPath.row
        return monthlyCell
    }

我还有一个扩展名。这给了我今天的一天Int

extension Date {
    static var nowDayAsInt: Int {
        let calendar = Calendar.current
        let component = calendar.dateComponents([.day], from: Date())
        return component.day!
    }
}

最后我在自己的类中更新自定义单元格的背景:

class MonthlyTableViewCell: UITableViewCell {
    if Date.nowDayAsInt == (self.tag + 1) {
            self.setDiagonalGradientBackground()
            self.makeRoundedCorners()
        }
}

self.setDiagonalGradientBackground()self.makeRoundedCorners()也来自UIView扩展,我认为名称是自我解释的。

结果:它始终设置两个或更多单元格背景颜色:

屏幕截图:https://imgur.com/a/FfzUgZO

我该如何解决这个问题?提前致谢

ios swift iphone uitableview date
1个回答
1
投票

单元格被重用,如果在特定条件下更改UI,则必须添加else子句来设置默认值

class MonthlyTableViewCell: UITableViewCell {
    if Date.nowDayAsInt == self.tag {
        self.setDiagonalGradientBackground()
        self.makeRoundedCorners()
    } else {
        // set default appearance
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.