我在Swift中制作了一个UIButton子类,以在选择时执行自定义绘图和动画
Swift - (void)setSelected:(BOOL)selected中的ObjC中的覆盖相当于什么?
- (void)setSelected:(BOOL)selected
我试过了
override var selected: Bool
所以我可以实现一个观察者,但是我得到
Cannot override with a stored property 'selected'
像其他提到的一样,您可以使用它willSet来检测更改。但是,在替代中,您不需要将值分配给super,而只是观察现有的更改。
willSet
您可以从以下游乐场观察到几件事:
willSet/didSet
get/set
.normal
.selected
selected
newValue
oldValue
didSet
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.