Swift UIButton 背景色不变

Swift UIButton background color does not change

我有以下自定义单元格:

class MyCell: UITableViewCell {

    func configure(title1: String, title2: String) {
        backgroundColor = .red

        let myView = MyView(frame: frame)
        myView.button1.setTitle(title1, for: .normal)
        myView.button2.setTitle(title2, for: .normal)

        addSubview(myView)
    }
}

和自定义视图:

class MyView: UIView {
    var button1: UIButton!
    var button2: UIButton!

    override var backgroundColor: UIColor? {
        didSet {
            guard UIColor.clear.isEqual(backgroundColor) else { return }
            button1.setTitle("asldkfa")
            button1.backgroundColor = .blue
            button2.backgroundColor = .yellow
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        button1 = UIButton()
        button2 = UIButton()
        button1.backgroundColor = .purple
        button2.backgroundColor = .brown
        backgroundColor = .gray

        let stackView = UIStackView(); stackView.distribution = .fill; stackView.alignment = .fill
        stackView.addArrangedSubview(button1)
        stackView.addArrangedSubview(button2)

        addSubview(stackView)
    }
}

我在我的 tableView:cellForRowAt 方法中初始化了单元格视图,如下所示:

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCell
cell.configure(title1: "Foo", title2: "Bla")

我在 tableView 中得到以下输出:

每次从外部更改 MyView 的颜色时(例如单击单元格时),我都希望更改按钮的颜色——这就是我覆盖 didSet 的原因MyViewbackgroundColor 的观察者。最终我希望这些颜色是随机的,但在这里我只是想改变 button1.backgroundColor = .blue.

不起作用,按钮的颜色没有改变。我什至尝试更改 tintColor,但它也不起作用。用 button1.setTitle(...) 更改标题确实有效,所以我不知道发生了什么。

有人知道吗?

提前致谢。

编辑

当我构建应用程序时,在 didSet 中添加 button1.setTitle("asldkfa", for: .normal),然后单击单元格,这是输出:

意味着 backgroundColor 已设置,因为标题确实发生了变化,只是颜色没有变化。

重要:没有其他代码显式更改了 backgroundColor,甚至没有实现 didSelectRowAt 方法。选择单元格时,其子视图的背景颜色会自动更新,这就是我现在通过选择单元格来更改颜色的方式。

实际上,问题是它 didSet 你添加了颜色所以当改变它时它会保持不变你应该这样做

 override var backgroundColor: UIColor? {
    didSet {
        button1.backgroundColor = backgroundColor
        button2.backgroundColor = backgroundColor
    }
}

更新: 而不是使用 UIButtonbackgroundColor 属性,你实际上想使用 setBackgroundImage(_:for:) .您可以使用 UIImage (extension example here) 上的扩展程序从颜色创建图像,这应该能很好地满足您的需求。

您生成的配置代码应如下所示:

button1.setBackgroundImage(.image(with: .red), for: .normal)