Swift UIButton子类和根据变量改变颜色

m1m5dgzv  于 2023-04-28  发布在  Swift
关注(0)|答案(2)|浏览(113)

我正在为我的UIButton使用一个子类,它有一个变量叫做isActive。我需要根据该变量更改按钮边框颜色。此变量将以编程方式更改。请帮我一下。

@IBDesignable
class buttonCTAOutlineDark: UIButton {

override init(frame: CGRect) {
    super.init(frame: frame)
    commonInit()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
}

override func prepareForInterfaceBuilder() {
    commonInit()
}

@IBInspectable var isActive: Bool {
    get {
        return self.isActive
    }
    set (active) {
        if active {
            commonInit(isActive: active)
        }
    }
}

func commonInit(isActive: Bool = false) {
    self.backgroundColor = .clear
    self.layer.cornerRadius = 4
    self.layer.borderWidth = 1

    if (isActive) {
        self.tintColor = ACTIVE_COLOR
        self.layer.borderColor = ACTIVE_COLOR.cgColor
    } else {
        self.tintColor = nil
        self.layer.borderColor = UIColor(red:0.69, green:0.72, blue:0.77, alpha:1.0).cgColor
    }
}
}
h9vpoimq

h9vpoimq1#

您应该观察didSet以更新view。在Swift中,类型名应该以大写e开头。g × ButtonCTAOutlineDark。请看固定类

@IBDesignable
class ButtonCTAOutlineDark: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    @IBInspectable var isActive: Bool = false {
        didSet {
            self.commonInit(isActive: self.isActive)
        }
    }

    func commonInit(isActive: Bool = false) {
        self.backgroundColor = .clear
        self.layer.cornerRadius = 4
        self.layer.borderWidth = 1

        if (isActive) {
            self.tintColor = ACTIVE_COLOR
            self.layer.borderColor = ACTIVE_COLOR.cgColor
        } else {
            self.tintColor = nil
            self.layer.borderColor = UIColor(red:0.69, green:0.72, blue:0.77, alpha:1.0).cgColor
        }
    }
}
gstyhher

gstyhher2#

您的isActive属性写入不正确。它首先不应该是计算属性。目前,getter只会导致无限递归,setter实际上并不设置任何东西。
isActive属性应该是具有didSet属性观察器的存储属性:

@IBInspectable
var isActive: Bool {
    didSet {

    }
}

didSet中,您可以只放置commonInit的最后一部分。commonInit的第一部分不需要在每次isActive更改时运行。我建议你将其提取为一个名为updateBorder的方法:

func updateBorder(isActive: Bool) {

    if (isActive) {
        self.tintColor = ACTIVE_COLOR
        self.layer.borderColor = ACTIVE_COLOR.cgColor
    } else {
        self.tintColor = nil
        self.layer.borderColor = UIColor(red:0.69, green:0.72, blue:0.77, alpha:1.0).cgColor
    }

}

然后在didSet中,你可以直接调用:

updateBorder(isActive: isActive)

相关问题