User User - 7 months ago 24
Swift Question

how to display alert controller only once when the UITextfield is tapped?

I'm trying to prevent user from manipulating with their data, so when they tap on

UITextfield
an
alertController
shall be displayed only once, after they press "yes" option, then they shall be able to change data. but instead of displaying alert controller once, it keeps displaying every time I tap on
UITextfield
; how I can solve this issue.

func textFieldDidBeginEditing(textField: UITextField) {
let alert = UIAlertController(title: "Warning !", message: "Are your sure you want to change your content? ", preferredStyle: .Alert)

let yes = UIAlertAction(title: "Yes", style: .Cancel) { (action) in

}
alert.addAction(yes)
let no = UIAlertAction(title: "No", style: .Default) { (action) in
}
alert.addAction(no)
presentViewController(alert, animated: true) {}
}
textField.becomeFirstResponder()
}

Answer
var alertWillShow = true

 func textFieldDidBeginEditing(textField: UITextField) {

if alertWillShow {
       alertWillShow = false

       let alert = UIAlertController(title: "Warning !", message: "Are your sure you want to change your content? ", preferredStyle: .Alert)

           let yes = UIAlertAction(title: "Yes", style: .Cancel) { (action) in

              }
               alert.addAction(yes)
              let no = UIAlertAction(title: "No", style: .Default) { (action) in
        }
               alert.addAction(no)
             presentViewController(alert, animated: true) {}
        }
}
 textField.becomeFirstResponder()
}
Comments