Disable UIContextualAction

290 Views Asked by At

I am trying to disable a UIContextualAction that I have:

let picture = UIContextualAction(style: .normal, title:  "  ", handler: { (ac: UIContextualAction, view: UIView, success:(Bool) -> Void) in
    // ...
})
picture.backgroundColor = .blue

I cant find anything online to enable or disable it, I still want it present, just don't want the user to tap on it. Is this possible?

3

There are 3 best solutions below

0
LinusGeffarth On BEST ANSWER

I'm not sure it can be disabled out-of-the-box, but as a workaround, you could have a global variable keeping track whether the action should be enabled and then check that in the action's handler:

var isCamActionEnabled = false // declare globally, if you need to set this from outside the current scope
let picture = UIContextualAction(style: .normal, title:  "  ", handler: { (ac: UIContextualAction, view: UIView, success:(Bool) -> Void) in
    guard isCamActionEnabled else { return }
    // ...
})
3
matt On

I still want it present, just don't want the user to tap on it

You can't prevent the user from tapping on the contextual action icon if it is present (what would you do, reach out and grab the user's hand?). However, just because the user taps on the contextual action doesn't mean you have to do anything in response.

The contextual action object has a completion handler; if you don't want to do anything in response to a tap, don't do anything in that completion handler.

let picture = UIContextualAction(style: .normal, title:  "  ", handler: { (ac: UIContextualAction, view: UIView, success:(Bool) -> Void) in
    // do nothing
})

However, I can't recommend this approach; it is extremely poor interface. If the user can see a thing, the user expects to be able to tap it and have it respond. A button that does nothing will feel "broken". It would be better to do what you said you didn't want to do, that is, under circumstances where the user should not be able to perform this action, don't show it in the first place.

0
Matea On

If you need to disable it after an user interaction, you can disable the view user's interactions till a next event occurs, for example, in my case, I had to disable the UIContextualAction to prevent a double tap till a request has finished:

let picture = UIContextualAction(style: .normal, title:  "  ", handler: { (ac: UIContextualAction, view: UIView, success:(Bool) -> Void) in
    view.isUserInteractionEnabled = false
    // create function with escaping completion handler and enable it again 
    exampleFunction() {
        view.isUserInteractionEnabled = true
    }
})