Search code examples
iosswiftxcodeuigesturerecognizerlayoutsubviews

Xcode button text is accessed but the background change UI is not reflected


I created a special button as below. I can access the text value when clicked, but when I change the background value, there is no change in the UI. Does anyone know why?

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
    }
}

Solution

  • Please remove these two lines from layoutSubviews

            titleLabel?.textColor = .white
            backgroundColor = .black
    

    Add it like this

    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 (_:))))
        }