skip to Main Content

or is there a way to check whether a UIControl has any UIActions?

Sometimes I want to change a UIControl’s behavior.
When using target-action, I can do it like this

button.removeTarget(nil, action: nil), for: .touchUpInside)
button.addTarget(self, action: #selector(didTouchUpInside()), for: .for: .touchUpInside)

3

Answers


  1. Why not you are using view.isUserInteractionEnabled = false? It will remove all the interaction ability of a view

    Login or Signup to reply.
  2. You can do this using enumerateEventHandlers:

    button.enumerateEventHandlers { action, targetAction, event, stop in
        if let action = action {
            // This is a UIAction
            button.removeAction(action, for: event)
        }
        if let (target, selector) = targetAction {
            // This is target / action
            button.removeTarget(target, action: selector, for: event)
        }
        stop = true // Ends iterating early if you are done
    }
    
    Login or Signup to reply.
  3. Taking what jrturton has said here, you can turn it into a small extension:

    extension UIButton {
        func removeAllActions() {
            enumerateEventHandlers { action, _, event, _ in
                if let action = action {
                    removeAction(action, for: event)
                }
            }
        }
    }
    

    And now you can just call removeAllActions() on your UIButton to have the same effect.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search