gpt4 book ai didi

ios - 访问了 Xcode 按钮文本,但未反射(reflect)背景更改 UI

转载 作者:行者123 更新时间:2023-12-01 16:05:16 24 4
gpt4 key购买 nike

我创建了一个特殊的按钮,如下所示。单击时我可以访问文本值,但是当我更改背景值时,UI 没有任何变化。有谁知道为什么吗?

class MyButton: UIButton {

override func layoutSubviews() {
super.layoutSubviews()

layer.cornerRadius = 8
titleLabel?.adjustsFontSizeToFitWidth = true
contentHorizontalAlignment = .center

titleLabel?.textColor = .white
backgroundColor = .black

addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:))))

}

@objc func someAction(_ sender:UITapGestureRecognizer) {
print(titleLabel!.text) // text accessible and printed

titleLabel?.textColor = .black //no change
backgroundColor = .white //no change
}
}

最佳答案

请从 layoutSubviews 中删除这两行

        titleLabel?.textColor = .white
backgroundColor = .black

这样添加

override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}

required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
layer.cornerRadius = 8
titleLabel?.adjustsFontSizeToFitWidth = true
contentHorizontalAlignment = .center

titleLabel?.textColor = .white
backgroundColor = .black

addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:))))
}

关于ios - 访问了 Xcode 按钮文本,但未反射(reflect)背景更改 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62874268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com