使用IBDesignable时,以下代码很常见,每次创建类时我都会重复,有没有办法避免这种重复?
override init(frame: CGRect) {
super.init(frame: frame)
themeProp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
themeProp()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
themeProp()
}
这就是我目前使用IBDesignable为UIButton创建样式的方法。
import UIKit
let colorWhite = colorLiteral(red: 0.9999127984, green: 1, blue: 0.9998814464, alpha: 1)
let colorLavender = colorLiteral(red: 0.6604440808, green: 0.5388858914, blue: 0.8827161193, alpha: 1)
@IBDesignable class PrimaryButtonA: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
themeProp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
themeProp()
}
func themeProp() {
setTitleColor(colorWhite, for:.normal)
self.layer.cornerRadius = 10
backgroundColor = colorLavender
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
themeProp()
}
}
@IBDesignable class PrimaryButtonB: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
themeProp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
themeProp()
}
func themeProp() {
setTitleColor(colorWhite, for:.normal)
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
themeProp()
}
}
由于我的知识有限,我尝试创建一个函数并尝试在每个类中调用它但它不起作用。
在每个类声明中重复这12行代码没有任何意义。所以,如果有办法避免这种重复,那么请使用我的代码来回答。
谢谢!
一种可能的解决方案是为这些视图创建一个公共超类。唯一的缺点是你必须为每种类型创建一个超类(UIView
s,UIButton
s等)
class DesignableView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
themeProp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
themeProp()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
themeProp()
}
func themeProp() { }
}
之后,使您的可设计类成为DesignableView
的子类。你只需要覆盖themeProp()
。