Mikey Mikey - 11 days ago 10
Swift Question

UIAlertController is disappearing automatically after short time

If a textfield is empty, I would like to make an

UIAlertController
to remind, that something has to be filled out in the textfield. Now I have the following code:

@IBAction func saveDetails(segue: UIStoryboardSegue) {

let dController = segue.source as? EntryTableViewController

if let text = dController?.bezeichnungTextField.text, text.isEmpty {

let alert = UIAlertController(title: "No description", message: "Please fill out description", preferredStyle: .alert)

let cancelAction = UIAlertAction(title: "OK", style: .default)

alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)

}else {

guard let menge = dController?.mengeTextField.text, let bezeichnung = dController?.bezeichnungTextField.text, let kategorie = dController?.categoryButtonOutlet.titleLabel?.text else {return}

self.saveItem(menge: menge, bezeichnung: bezeichnung, kategorie: kategorie)
self.tableView.reloadData()
}
}


Now actually it works when I press the button to return to the first controller. But the
UIAlertController
only appears for a very short moment and then disappears automatically. Is there a mistake in my code or isn't it possible to call the
UIAlertController
on a
unwind segue
?

Thank you for your help

Answer

You just show the alert controller and then immediately unwind. The solution is to check for the empty textfield before unwinding.

Make IBAction for your button then check the textfield if it is empty and then perforn your segue programmatically.

Comments