ios - 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
}
}
}
解决方案
您应该观察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
}
}
}
推荐阅读
- makefile - make : 过滤显示以仅显示错误
- postgresql - PostgreSQL - 模式匹配 - 字符串到子字符串
- ruby-on-rails - 同一类中包含具有相同方法名称的两个模块
- qt - 接受/拒绝未捕获的对话信号
- asp.net-mvc - 无法运行 npm run wbp
- docker - Kubernetes Docker Hub 私有
- hyperledger-composer - Hyperledger Composer Playground 查询
- python - 当我尝试在网格上实现函数时出现 TypeError
- mule - Mule 中的 salesforce 连接器 - SOQL 长查询对于某些对象无法正常工作 - 例如 product2
- java - 序列化后,Hashcode 更改为用作 HashMap 键的 Object