访问 Xcode 按钮文本但未反映背景更改 UI
Posted
技术标签:
【中文标题】访问 Xcode 按钮文本但未反映背景更改 UI【英文标题】:Xcode button text is accessed but the background change UI is not reflected 【发布时间】:2020-07-13 10:49:54 【问题描述】:我创建了一个特殊按钮,如下所示。单击时我可以访问文本值,但是当我更改背景值时,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
【问题讨论】:
【参考方案1】:请从 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 (_:))))
【讨论】:
以上是关于访问 Xcode 按钮文本但未反映背景更改 UI的主要内容,如果未能解决你的问题,请参考以下文章
Razor 页面:如何动态更改按钮属性(颜色、文本)以反映后端更改