我在UIButton上遇到了一个奇怪的问题。我有以下自定义类:
import UIKit
@IBDesignable class ToggleButton: UIButton {
@IBInspectable var state1Image: UIImage = UIImage()
@IBInspectable var state2Image: UIImage = UIImage()
@IBInspectable var someString: String = ""
private var toogleOn: Bool = false {
didSet {
if toogleOn {
isSelected = true
} else {
isSelected = false
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
print("test")
print("some string is \(someString)")
}
@objc func didToggleButton() {
toogleOn = !toogleOn
}
}
在界面构建器中,我设置了可检查的变量,假设我将someString
设置为hello。现在,当我运行应用程序并查看日志时,变量的print
是""
。我也无法设置图像。它仅使用默认值,而不会使用我设置的新值。我在这里做错了什么?
答案 0 :(得分:1)
尝试一下:
@IBDesignable class ToggleButton: UIButton {
@IBInspectable var state1Image: UIImage = UIImage() {
didSet {
setup()
}
}
@IBInspectable var state2Image: UIImage = UIImage() {
didSet {
setup()
}
}
@IBInspectable var someString: String = "" {
didSet {
setup()
}
}
override func prepareForInterfaceBuilder() {
setup()
}
private func setup() {
print("test")
// Updating title label as someString to see the update
self.titleLabel?.text = someString
}
private var toogleOn: Bool = false {
didSet {
if toogleOn {
isSelected = true
} else {
isSelected = false
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
@objc func didToggleButton() {
toogleOn = !toogleOn
}
}