Cirked
Cirked

Reputation: 17

UIAlertController Keeps Re-Appearing After Closing It

I have written code for an alert to appear when the input in one of my UITextFields is less than 1050. It successfully appears when the inputs satisfies that, but after I press "OK" it instantly re-appears.

Below is the code in the viewDidLoad function:

override func viewDidLoad(){
    super.viewDidLoad()
    alert = UIAlertController(title: "Error", message: "Please enter an exit width value greater than 1050", preferredStyle: UIAlertControllerStyle.Alert)
    let okay = UIAlertAction(title: "OK", style: UIAlertActionStyle.Destructive, handler: valueCalc)
    alert.addAction(okay)
}

Then I have in my valueCalc function (which is called when a button is tapped):

@IBAction func valueCalc(sender: AnyObject){
    if(Int(mmText.text!)! < 1050){ //mmText is an UITextField
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

Upvotes: 0

Views: 222

Answers (3)

Ishika
Ishika

Reputation: 2205

According to your line of code

let okay = UIAlertAction(title: "OK", style: UIAlertActionStyle.Destructive, handler: valueCalc)

Your handler name valueCalc is called when you press OK.

Again the value is calculated which when come out be less then the specified characters shows back you the alert.

Instead of that, replace this line in your code -

let okay = UIAlertAction(title: "OK", style: UIAlertActionStyle.Destructive, handler: handlerMethod)

and add this method to your code

func handlerMethod() {

   //handle your action here after ok is pressed for e.g if you wanna just dismiss the alert then write

   dismissViewControllerAnimated(true, completion: nil)

}

Upvotes: 5

Anil Kumar
Anil Kumar

Reputation: 955

Try this

    override func viewDidLoad(){
    super.viewDidLoad()
    alert = UIAlertController(title: "Error", message: "Please enter an exit width value greater than 1050", preferredStyle:      UIAlertControllerStyle.Alert)

    let okay = UIAlertAction(
        title: "OK",
        style: UIAlertActionStyle.Destructive) { (action) in }

    }

    @IBAction func valueCalc(sender: AnyObject){
    if(Int(mmText.text!)! < 1050){ //mmText is an UITextField
    self.presentViewController(alert, animated: true, completion: nil)
    }

Upvotes: 0

Cocoatype
Cocoatype

Reputation: 2570

You have the handler argument for your UIAlertAction set to valueCalc. Therefore, whenever the user taps "OK", the method valueCalc gets run again, and since the value is (presumably) still the same, the alert is presented right back again.

Upvotes: 1

Related Questions