gpt4 book ai didi

ios - Swift UIButton 子类化并根据变量改变颜色

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:14 25 4
gpt4 key购买 nike

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

最佳答案

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

关于ios - Swift UIButton 子类化并根据变量改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53532975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com