Xcode 按钮文本已访问,但背景更改 UI 未反映

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

我创建了一个特殊的按钮,如下所示。单击时我可以访问文本值,但是当我更改背景值时,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 (_:))))
    }