FS.O6
FS.O6

Reputation: 1464

Disable touch outside UIAlertController frame to cancel

I have a UIAlertController with a style of ActionSheet.

I've added a cancel action to it.

The thing is that for some reason when the user taps outside of the ActionSheet box - the alert is dismissed.

How can I disable this behavior? I want the user to press the cancel button directly.

Upvotes: 1

Views: 1575

Answers (1)

FRIDDAY
FRIDDAY

Reputation: 4179

swift 4 / Xcode 11

Hi. To disable user interaction (example: tapping anywhere but the cancel button), call the present method in your alert function and set it's completion closure as below code.

present(alertController, animated: true) {
   alertController.view.superview?.subviews[0].isUserInteractionEnabled = false
}

The whole example:

func alertMe() {

let alertController = UIAlertController(title: "Tapping Test", message: "User Interaction on the view is disabled", preferredStyle: .actionSheet)

let cancelAction = UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel) { UIAlertAction in

// do something/call someone/or nothing :)
NSLog("cancel Button is Pressed")

}

alertController.addAction(cancelAction)

present(alertController, animated: true){
            alertController.view.superview?.subviews[0].isUserInteractionEnabled = false
    }
}

Upvotes: 2

Related Questions