本文介绍了Swift - UIButton重写setSelected的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在Swift中创建一个UIButton子类,以便在选择时执行自定义绘图和动画
I'm making a UIButton subclass in Swift to perform custom drawing and animation on selection
在Swift中覆盖的等价物是什么? - (void)setSelected:(BOOL)在ObjC中选择
?
我试过
覆盖var选择: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
仍然为<$ c $调用super C>获取/设置。您可以判断,因为状态从.normal
更改为.selected
。 - 即使值未更改,也会调用willSet和didSet,因此您可能希望将
selected
的值与newValue进行比较
inwillSet
或oldValue
indidSet
确定是否要制作动画。
- Overriding a property for
willSet/didSet
still calls super forget/set
. You can tell because the state changes from.normal
to.selected
. - willSet and didSet are called even when the value is not changing, so you will probably want do the compare the value of
selected
to eithernewValue
inwillSet
oroldValue
indidSet
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!