KexAri KexAri - 1 month ago 21
iOS Question

isHighlighted called multiple times on UIButton

I have subclassed

UIButton
and want to call a delegate method just once when the button goes into the highlighted state and call it again just once when it goes into the unhighlighted state:

override var isHighlighted: Bool {
didSet {
if isHighlighted {
delegate?.buttonHighlightStateDidChange(highlighted: true)
} else {
delegate?.buttonHighlightStateDidChange(highlighted: false)
}
}
}


However when I touch down on the button it seems that didSet is getting repeatedly called. What am I doing wrong here? How can I call the delegate method just once?

Answer

I would recommend against using your subclass in this way. UIControl has a builtin mechanism for getting callbacks in response to control events:

func registerActions(for button: UIButton) {
    button.addTarget(self, action: #selector(MyClass.buttonIsHighlighted(sender:)), for: .touchDown)

    button.addTarget(self, action: #selector(MyClass.buttonIsUnHighlighted(sender:)), for: .touchUpInside)
    button.addTarget(self, action: #selector(MyClass.buttonIsUnHighlighted(sender:)), for: .touchUpOutside)
}

func buttonIsHighlighted(sender: UIButton) {
    // highlighted
}

func buttonIsUnHighlighted(sender: UIButton) {
    // unhighlighted
}