Swift UIButton子类并根据变量更改颜色

时间:2018-11-29 06:22:25

标签: ios swift uibutton subclass programmatically

我正在为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
    }
}
}

2 个答案:

答案 0 :(得分:3)

您应该观察didSet来更新view。在Swift中,类型名称应以大写字母开头,例如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
        }
    }
}

答案 1 :(得分:2)

您的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)