iosswiftuitextfielduicontroleventsaddtarget

How can I override addTarget in a UITextField for only UIControlEvent.allEditingEvents?


How can I override the addTarget function inside the UITextField class, but only for UIControlEvent.allEditingEvents?

The function is like this, however I am not sure how to apply it only for a specific control event.

override func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents) {
    <#code#>
}

Solution

  • You should call super.addTarget and only call your custom code if controlEvents equals to .allEditingEvents.

    override func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents) {
        super.addTarget(target, action: action, for: controlEvents)
    
        if controlEvents == .allEditingEvents {
            [your code]
        }
    }