我有以下自定义单元格:
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
观察者。最终我希望这些颜色是随机的,但在这里我只是想改变。backgroundColor
MyView
button1.backgroundColor = .blue
它不起作用,按钮的颜色不会改变。我什至尝试过更改tintColor
它,它也不起作用。更改标题button1.setTitle(...)
确实有效,所以我不知道发生了什么。
有人有想法吗?
提前致谢。
编辑
当我构建应用程序时,在button1.setTitle("asldkfa", for: .normal)
中添加didSet
,然后单击单元格,这是输出:
这意味着backgroundColor
已设置,因为标题确实发生了变化,而不是颜色。
重要提示:没有其他代码backgroundColor
显式更改,didSelectRowAt
甚至没有实现该方法。选择单元格时,其子视图的背景颜色会自动更新,这就是我现在通过选择单元格来更改颜色的方式。