我在Swift中创建一个UIButton子类,以便在选择时执行自定义绘图和动画
在ObjC中覆盖- (void)setSelected:(BOOL)selected
的Swift中等效的是什么?
我试过
override var selected: Bool
所以我可以实现一个观察者,但我得到了
Cannot override with a stored property 'selected'
答案 0 :(得分:56)
与其他人一样,您可以使用willSet
来检测更改。但是,在覆盖中,您不需要将值分配给super,而只是观察现有的更改。
您可以在以下游乐场观察几件事:
willSet/didSet
的属性仍会为get/set
调用超级。您可以判断,因为状态从.normal
更改为.selected
。selected
的值与newValue
或willSet
中的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.
答案 1 :(得分:6)
class MyButton : UIButton {
// ...
override var isSelected: Bool {
willSet(newValue) {
super.isSelected = newValue;
// do your own business here...
}
}
// ...
}
答案 2 :(得分:0)
试试这个
override public var selected: Bool {
willSet(selectedValue) {
self.selected = selectedValue
// Do whatever you want
}
}
答案 3 :(得分:-1)
以快速语言创建IBAction和检查按钮。
@IBAction func favoriteButtonAction(sender: UIButton) {
// Save Data
sender.selected = !sender.selected;
if (sender.selected)
{
NSLog(" Not Selected");
}
else
{
NSLog(" Selected");
}
}