【问题标题】:Xcode button text is accessed but the background change UI is not reflected访问 Xcode 按钮文本但未反映背景更改 UI
【发布时间】: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
    }
}

【问题讨论】:

    标签: ios swift xcode uigesturerecognizer layoutsubviews


    【解决方案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 (_:))))
        }
    

    【讨论】:

      猜你喜欢
      • 2013-10-24
      • 2012-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多