我正在 Swift 中创建一个 UIButton 子类,以在选择时执行自定义绘图和动画
I'm making a UIButton subclass in Swift to perform custom drawing and animation on selection
在 Swift 中,在 ObjC 中覆盖 - (void)setSelected:(BOOL)selected
的等价物是什么?
What would be the equivalent in Swift of overriding - (void)setSelected:(BOOL)selected
in ObjC?
我试过了
覆盖 var selected: Bool
所以我可以实现一个观察者,但我得到了
so I could implement an observer but I get
不能用存储的属性'selected'覆盖
和其他人提到的一样,您可以使用 willSet
来检测更改.但是,在覆盖中,您不需要将值分配给 super,您只是在观察现有的更改.
Like others mentioned you can use willSet
to detect changes. In an override, however, you do not need assign the value to super, you are just observing the existing change.
您可以从以下游乐场观察到几件事:
A couple things you can observe from the following playground:
willSet/didSet
的属性仍会为 get/set
调用 super.您可以判断,因为状态从 .normal
变为 .selected
.selected
的值与 willSet 中的 newValue
进行比较
或 oldValue
中的 didSet
来确定是否进行动画处理.willSet/didSet
still calls super for get/set
. You can tell because the state changes from .normal
to .selected
.selected
to either newValue
in willSet
or oldValue
in didSet
to determine whether or not to animate.import UIKit
class MyButton : UIButton {
override var isSelected: Bool {
willSet {
print("changing from (isSelected) to (newValue)")
}
didSet {
print("changed from (oldValue) to (isSelected)")
}
}
}
let button = MyButton()
button.state == .normal
button.isSelected = true // Both events fire on change.
button.state == .selected
button.isSelected = true // Both events still fire.
这篇关于Swift - UIButton 覆盖 setSelected的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!