【问题标题】:Can't change the backgroundColor of a UILabel in a Static Cell无法更改静态单元格中 UILabel 的背景颜色
【发布时间】:2018-12-27 19:45:23
【问题描述】:

我有一个带有静态单元格的表格视图。在那里我选择了样式Right Detail

现在我想更改右侧Detail 标签的背景颜色。即使它只是一个标签,我也无法更改 IB 中的背景颜色。

所以我把它拉到一个视图控制器中以编程方式完成。

@IBOutlet weak var ukPremiumLabel: UILabel!

override func viewDidLoad() {
        super.viewDidLoad()
        ukPremiumLabel.layer.backgroundColor = UIColor(red: 0/255, green: 159/255, blue: 184/255, alpha: 1.0).cgColor
}

我也试过这样:

override func viewDidLoad() {
        super.viewDidLoad()
        ukPremiumLabel.backgroundColor = UIColor.blue
}

我不知道为什么它仍然是白色的。

【问题讨论】:

  • 试试看。你会感到惊讶。它完全忽略它,因为它也以编程方式进行。似乎detailTextLabel 以某种方式被覆盖了。接受的解决方案虽然有效。
  • 好的,我现在明白了。这是因为您使用了内置样式。

标签: ios swift xcode uilabel


【解决方案1】:

您使用的是内置的UITableViewCell 样式,因此单元格的detailTextLabelbackgroundColor 在创建单元格后会以某种方式被覆盖。

你可以通过改变这个颜色属性来解决它。

为此,您可以在 UITableViewController 的覆盖 willDisplay 方法中更改此颜色

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if cell.detailTextLabel == ukPremiumLabel {
        ukPremiumLabel.backgroundColor = .blue
    }
}

【讨论】:

  • 为什么要使用 willdisplay 委托?而不是 cellforrow?
  • @ktrkathir 如果您使用的是静态单元格,则不必对任何东西使用 cellForRowAt 方法,因此在 willDisplay 内更改它更容易(您必须获得参考单元格,在willDisplay 中,您有单元格的参考作为方法的参数)。 willDisplay 也非常适合进行“美容”更改 (developer.apple.com/documentation/uikit/uitableviewdelegate/…)
【解决方案2】:

UILabel可以使用IBDesignable/IBInspectable注解,

@IBDesignable
class BackgroundLabel: UILabel {
    @IBInspectable var persistentBackgroundColor: UIColor = UIColor.red {
        didSet {
            super.backgroundColor = persistentBackgroundColor
        }
    }

    override var backgroundColor: UIColor? {
        didSet {
            if backgroundColor != persistentBackgroundColor {
                backgroundColor = persistentBackgroundColor
            }
        }
    }
}

UITableViewCell 中,将BackgroundLabel 分配给detailTextLabel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2013-04-12
    • 2021-10-31
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多