【发布时间】:2021-08-19 04:27:33
【问题描述】:
我一直在尝试为我的自定义组件实现主题逻辑。我将以 ZFButton 为例。
当应用程序启动时,我实例化 ZFbutton 并设置我希望这个主题具有的任何特征:
let theme = ZFButton()
theme.backgroundColor = .red //UIButton property
theme.cornerRadius = 8 //ZFButton property
theme.borderColor = .green //ZFButton property
theme.borderWidth = 1 //ZFButton property
然后将其添加到主题数组中:
ZFButton.themes.append(theme)
驻留在ZFButton中如下:
public static var themes = [ZFButton]()
在我的 ZFButton 中,我有以下属性,它允许我从 IB 属性检查器中选择我想为那个特定的 ZFButton 使用哪个主题
@IBInspectable public var theme: Int = 0 { didSet { self.setupTheme() } }
最后,一旦设置了主题属性,就会调用 setupTheme(),在其中我尝试将给定主题的所有属性中设置的值复制到 ZFButton 的这个特定实例中。为此我使用反射:
private func setupTheme() {
if ZFButton.themes.count > self.theme {
let theme = ZFButton.themes[self.theme]
let mirror = Mirror(reflecting: theme)
for child in mirror.children {
if let label = child.label,
label != "theme", //check to prevent recursive calls
self.responds(to: Selector(label)) {
self.setValue(child.value, forKey: label)
print("Property name:", child.label)
print("Property value:", child.value)
}
}
}
}
现在我有两个问题:
1 - 具有 setter/getter 的属性不会显示在反射中,例如:
@IBInspectable public var borderColor: UIColor {
set { layer.borderColor = newValue.cgColor }
get { return UIColor(cgColor: layer.borderColor!) }
}
而使用 didSet 的属性,例如:
@IBInspectable public var iconText: String = "" { didSet { self.setupIcon() } }
但是,我确实需要一个 getter 来在 layer 中返回 borderColor。
2 - 使用 Mirror 反映所有 ZFButton 属性时,除了 (1) 中描述的问题外,我也没有获取 UIButton 属性,是否也可以获取 ZFButton 的超类(UIButton)属性?
【问题讨论】:
标签: swift reflection getter-setter mirror