我正在制作演示以了解@IBInspectable 的工作原理。
首先,我在 UIViewController 子类中创建了两个变量:
@IBInspectable var intTest:Int = 10
@IBInspectable var flag:Bool = false
以便它出现在 Storyboard 中。之后,我更改 Storyboard中这些变量的值:
然后,我尝试像这样在“viewDidLoad()”方法中打印这些变量:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("intTest value: \(String(describing: intTest))")
print("flag value: \(String(describing: flag)))")
}
输出是:
intTest value: 90
flag value: true
它工作正常,除非我像这样更改变量声明,
@IBInspectable var intTest:Int? = 10
@IBInspectable var flag:Bool? = false
之后,我在 Storyboard中更改了与上面相同的值,但值没有改变。
输出是:
intTest value: Optional(10)
flag value: Optional(false)
所以我的问题是,当我将变量声明为可选时,为什么值没有更新?
另一件事是,当我将变量作为字符串时,值会更新。谁能帮我理解这个功能?
最佳答案
设置可选值 IBInspectable
var
@IBInspectable var placeHolderImage:UIImage? {
didSet {
leftViewSetting()
}
}
设置默认值 IBInspectable
var
@IBInspectable var placeHolderImage:UIImage = UIImage() {
didSet {
leftViewSetting()
}
}
使用这种方法,每次您在 Interface Builder` 中更改值时,您的 View 都会更新。
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
关于ios - 为什么 IBInspectable 不为 Storyboard 中的可选变量设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43774279/