I\'m making a UIButton subclass in Swift to perform custom drawing and animation on selection
What would be the equivalent in Swift of overriding - (void)setSe
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
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.
try this
override public var selected: Bool {
willSet(selectedValue) {
self.selected = selectedValue
// Do whatever you want
}
}
you'd do it like e.g. this:
class MyButton : UIButton {
// ...
override var isSelected: Bool {
willSet(newValue) {
super.isSelected = newValue;
// do your own business here...
}
}
// ...
}
Create IBAction and check button selected or not in swift language.
@IBAction func favoriteButtonAction(sender: UIButton) {
// Save Data
sender.selected = !sender.selected;
if (sender.selected)
{
NSLog(" Not Selected");
}
else
{
NSLog(" Selected");
}
}