Swift - UIButton overriding setSelected
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:
- 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 UIKitclass 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 == .normalbutton.isSelected = true // Both events fire on change.button.state == .selectedbutton.isSelected = true // Both events still fire.