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

标签 ios uitableview colors custom-cell

我的 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/

相关文章:

ios - 你能在 UIViewController 类中实现辅助功能方法吗?

ios - Xcode Scheme 默认位置在测试中被忽略

ios - TableView 在重新加载时显示重复的单元格

css - @media (color) 失败的颜色

Vim 状态行不会从表达式中扩展颜色/高亮组

ios - 日历应用程序想要快速与 ios 日历同步

objective-c - 如何使用导航栏外的按钮创建推送转场?

ios - 为不同的设备调整 UItableview 的大小

具有自动布局和偏移约束的 UITableView

CSS 过渡效果::文本改变颜色,但不改变边框