Swift - UIButton重写setSelected

时间:2014-10-14 15:44:00

标签: ios swift uibutton subclass

我在Swift中创建一个UIButton子类,以便在选择时执行自定义绘图和动画

在ObjC中覆盖- (void)setSelected:(BOOL)selected的Swift中等效的是什么?

我试过

override var selected: Bool

所以我可以实现一个观察者,但我得到了

Cannot override with a stored property 'selected'

4 个答案:

答案 0 :(得分:56)

与其他人一样,您可以使用willSet来检测更改。但是,在覆盖中,您不需要将值分配给super,而只是观察现有的更改。

您可以在以下游乐场观察几件事:

  1. 覆盖willSet/didSet的属性仍会为get/set调用超级。您可以判断,因为状态从.normal更改为.selected
  2. 即使值未更改,也会调用willSet和didSet,因此您可能希望将selected的值与newValuewillSet中的oldValue进行比较在didSet中确定是否要制作动画。
  3. 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");
    }

}