Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Alert action from dismissing the UIAlertController if incorrect answer - Swift 4

I have a simple Parent Gateway for child friendly game using a UIAlertController.

When the user answers the question incorrectly - I DONT want the alert view to be dismissed, at the moment I have the device vibrate and the screen shake but I can't get the alert view to stay on the screen.

The answers provided are in Obj-C or involve disabling the button, which obviously won't work and the other answers do not work - so I was hoping there would be an updated answer.

func parentGate () {

    var val1 = [1,2,3,4]
    var val2 = [5,6,7,8]
    let valIndex1 = Int(arc4random_uniform(UInt32(val1.count-1)))
    let valIndex2 = Int(arc4random_uniform(UInt32(val2.count-1)))

    accessAnswer = val1[valIndex1]+val2[valIndex2]

    let alertController = UIAlertController (title: "Parental Control", message: "This section is for Parents only, \nplease answer the question below: \nWhat is \(val1[valIndex1]) + \(val2[valIndex2])?", preferredStyle: .alert)
    let testAnswer = UIAlertAction(title: "OK", style: .default, handler: answerHandler)
    let cancelAnswer = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

    alertController.addTextField(configurationHandler: answerTextFieldResult)
    alertController.addAction(testAnswer)
    alertController.addAction(cancelAnswer)

    self.present(alertController, animated: true, completion: nil)

}

and then the testAnswer handler looks like this:

func answerHandler (alert: UIAlertAction) {

    guard  let suppliedAnswer = answerTextField?.text,
        let answer = Int(suppliedAnswer) else {
            return
    }

    if answer == accessAnswer {
        print ("Good")

    } else {
        print ("Bad")
        AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
        self.view.shake(count: 3, for: 0.3, withTranslation: 3)
    }
}

If you want to see what the textField handler looks like at the moment:

func answerTextFieldResult(textfield: UITextField) {
    answerTextField = textfield
    answerTextField?.placeholder = "Answer"
} 
like image 718
Brewski Avatar asked Feb 02 '26 23:02

Brewski


1 Answers

You can't do this. It's system behaviour - when you click on button alert closes and you can't prevent this.

Only one solution is to create a custom view controller that will look like native UIAlertController.

like image 181
Ivan Smetanin Avatar answered Feb 04 '26 15:02

Ivan Smetanin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!