Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

ios - Swift - UIButton overriding setSelected

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)setSelected:(BOOL)selected in ObjC?

I tried

override var selected: Bool

so I could implement an observer but I get

Cannot override with a stored property 'selected'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. Overriding a property for willSet/didSet still calls super for get/set. You can tell because the state changes from .normal to .selected.
  2. 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 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...