gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 04:45:17 26 4
gpt4 key购买 nike

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

单元格中有一个空标签和一个文本标签。通过将 backgroundColor 设置为一些 R、G、B 颜色,可以简单地为空标签着色。

但是,当我选择和取消选择表格中的行时,标签的背景颜色消失了。这种情况一直发生,直到我将单元格滚动出 View 并再次回到 View 中,此时它再次显示颜色。

下面是一些截图来说明发生了什么:

这是选择颜色之前的样子 Before Selecting a Color

这是我选择颜色后的样子 - 它似乎将标签背景颜色更改为透明。它不应该这样做 Selecting one color

这是我选择不同颜色后的样子 - 颜色保持透明/白色 Selecting another color

当然,我不希望这样的事情发生。目的是让标签颜色保持不变。

这是我的 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
}

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

cell.colourIndicatorLabel.backgroundColor = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(brightness))

非常感谢您的帮助!我知道我不太擅长在 SO 上提问,所以如果您有任何问题,请提问! ;)

最佳答案

当一个单元格被选中时,iOS 会清除所有单元格 subview 的背景颜色。您可以通过覆盖 UITableViewCell 子类上的 setSelected 方法来避免这种情况:

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

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

关于ios - 在 Swift 中选择行时删除标签背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35515098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com