标签背景在Swift中选择行时删除了颜色

ben*_*_uk 5 colors uitableview custom-cell ios

我的Swift应用程序遇到了一个奇怪的问题.我正在尝试创建一个UITableViewCell使用我创建的自定义单元格.

我在单元格中有一个空标签和一个文本标签.通过设置backgroundColor一些R,G,B颜色,可以简单地对空标签进行着色.

但是,当我在表格中选择和取消选择行时,标签的背景颜色会消失.这种情况发生,直到我将单元格滚出视图并再次返回视图,然后再次向我显示颜色.

这里有一些截图来说明发生了什么:

这是在选择颜色之前的样子 在选择颜色之前

这是我选择颜色时的样子 - 它似乎将标签背景颜色更改为透明.它不应该这样做 选择一种颜色

这是我选择不同颜色时的样子 - 颜色保持透明/白色 选择另一种颜色

当然,我不希望这种情况发生.目的是使标签颜色保持不变.

这是我的代码 cellForRowAtIndexPath

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ScenesTableCell
    cell.sceneNameLabel.text = scenesArr[indexPath.row].sceneName
    let red = scenesArr[indexPath.row].sceneCol[0]
    let green = scenesArr[indexPath.row].sceneCol[1]
    let blue = scenesArr[indexPath.row].sceneCol[2]
    let brightness = scenesArr[indexPath.row].sceneBrightnessMultiplier
    cell.colourIndicatorLabel.layer.backgroundColor = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(brightness)).CGColor
    cell.colourIndicatorLabel.layer.cornerRadius = 5
    cell.colourIndicatorLabel.layer.borderWidth = 1
    cell.colourIndicatorLabel.layer.borderColor = UIColor(red: 77.0/255.0, green: 146.0/255.0, blue: 203.0/255.0, alpha: 1.0).CGColor
}
Run Code Online (Sandbox Code Playgroud)

请注意,我已经尝试了以下代码行来更改backgroundColor,但是同样的事情发生了,但它填充了圆形边框之外:

cell.colourIndicatorLabel.backgroundColor = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(brightness))
Run Code Online (Sandbox Code Playgroud)

我非常感谢这里的一些帮助!我知道我不太擅长提问,所以如果您有任何疑问,请询问!;)

Hri*_*sto 3

当选择一个单元格时,iOS 会清除所有单元格子视图的背景颜色。您可以通过重写子类setSelected上的方法来避免这种情况UITableViewCell

extension ScenesTableCell {
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.colourIndicatorLabel.backgroundColor = .blue // Set with the color you need
    }
}
Run Code Online (Sandbox Code Playgroud)

为了使用圆角并且UIView.backgroundColor不溢出,可以cell.colourIndicatorLabel.clipsToBounds = true在使单元出列时或在单元子类中设置。