首页 > 解决方案 > Swift UIButton 子类并根据变量更改颜色

问题描述

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

标签: iosswiftuibuttonsubclassprogrammatically

解决方案


您应该观察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
        }
    }
}

推荐阅读