ios - 访问 Xcode 按钮文本但未反映背景更改 UI
问题描述
我创建了一个特殊按钮,如下所示。单击时我可以访问文本值,但是当我更改背景值时,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 (_:))))
}
推荐阅读
- java - 替换事务后如何保持片段状态?
- json - 找不到密钥时使用 JQ“包含”并抑制错误
- elasticsearch - 在可视化之前编辑数据
- sql-server - SQL 电子邮件通知
- angular - Angular 和 Stackblitz
- .net - 是否可以在高级安装程序中从安装程序执行某些命令之前和之后将文件复制到用户计算机?
- sql-server - 如何分配百分比金额项目
- javascript - Angular 7:防止在通过数据绑定传递给子组件的字符串变量中转义 HTML 标签
- android - 如何在android-navigation lib上隐藏BottomNavigationView
- unit-testing - Spring Boot 2.1.1:java.lang.IllegalStateException:运行单元测试时无法检索@EnableAutoConfiguration 基本包错误