E. Tess E. Tess - 3 years ago 91
Swift Question

Why doesn't my alert view controller work

let alert = UIAlertController(title: "Title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Title", style: UIAlertActionStyle.default, handler: { action in self.alertFunc() }))


If I build this the alert view doesn't appear. What have I missed?

P.S. I know there are some similar question but to find out what they have and I have missed is hard

Answer Source

You need to present it too on your current context:

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

Add that row at the end of your alert declaration:

let alert = UIAlertController(title: "Title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Title", style: UIAlertActionStyle.default, handler: { action in 
    self.alertFunc() 
}))
self.present(alert, animated: true, completion: nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download