-1

我有以下自定义单元格:

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外部更改的颜色时(例如单击单元格时),我想更改按钮的颜色——这就是为什么我覆盖了in的didSet观察者。最终我希望这些颜色是随机的,但在这里我只是想改变。backgroundColorMyViewbutton1.backgroundColor = .blue

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

有人有想法吗?

提前致谢。

编辑

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

在此处输入图像描述

这意味着backgroundColor已设置,因为标题确实发生了变化,而不是颜色。

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

4

2 回答 2

2

更新:您实际上想要使用 ,而不是使用UIButton'属性。您可以使用扩展(此处的扩展示例)从颜色创建图像,这应该适用于您正在尝试做的事情。backgroundColorsetBackgroundImage(_:for:)UIImage

您生成的配置代码应类似于:

button1.setBackgroundImage(.image(with: .red), for: .normal)
于 2018-08-30T16:23:14.400 回答
-3

实际上,问题在于您添加了颜色,所以在更改它时将保持不变,您应该这样做

 override var backgroundColor: UIColor? {
    didSet {
        button1.backgroundColor = backgroundColor
        button2.backgroundColor = backgroundColor
    }
}
于 2018-08-30T15:36:17.367 回答