ios Swift - UIButton 覆盖 setSelected
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26364869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - UIButton overriding setSelected
提问by LorTush
I'm making a UIButton subclass in Swift to perform custom drawing and animation on selection
我正在 Swift 中创建一个 UIButton 子类来在选择时执行自定义绘图和动画
What would be the equivalent in Swift of overriding - (void)setSelected:(BOOL)selected
in ObjC?
在 Swift 中重写- (void)setSelected:(BOOL)selected
ObjC的等价物是什么?
I tried
我试过
override var selected: Bool
override var selected: Bool
so I could implement an observer but I get
所以我可以实现一个观察者,但我得到
Cannot override with a stored property 'selected'
Cannot override with a stored property 'selected'
回答by Brian Nickel
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.
像其他人提到的那样,您可以willSet
用来检测更改。但是,在覆盖中,您不需要将值分配给 super,您只是在观察现有的更改。
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.
- 覆盖 for 的属性
willSet/didSet
仍然调用 super forget/set
。您可以判断是因为状态从.normal
变为.selected
。 - willSet和didSet被称为甚至当值没有改变,所以你可能会想要做比较的价值
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.
回答by holex
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...
}
}
// ...
}
回答by diegomen
try this
尝试这个
override public var selected: Bool {
willSet(selectedValue) {
self.selected = selectedValue
// Do whatever you want
}
}
回答by Anit Kumar
Create IBAction and check button selected or not in swift language.
创建 IBAction 并检查是否以 swift 语言选中按钮。
@IBAction func favoriteButtonAction(sender: UIButton) {
// Save Data
sender.selected = !sender.selected;
if (sender.selected)
{
NSLog(" Not Selected");
}
else
{
NSLog(" Selected");
}
}