Reputation: 885
I want to navigate back to root view controller when someone says ok to the alert action. But the Alert action does not allow to access self.
What is the work around to get current navigation controller in AlertAction,
here is the code,
func buttonAction(sender:UIButton!)
{
let alertController = UIAlertController(title: "IQ", message:"Thank you for your feedback!", preferredStyle: .Alert)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
var okAction = UIAlertAction(title: "Menu", style:UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
self.navigationController?.popToRootViewControllerAnimated(true) //error
}
Upvotes: 0
Views: 778
Reputation: 40028
All you have to do is to define a getter for the okAction
property.
var okAction: UIAlertAction {
get {
return UIAlertAction(title: "Menu", style:UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
Tested in Xcode 7.1.1
Upvotes: 1
Reputation: 5300
You need to dismiss the presented view controller (the Alert) before you try to pop from the navigation controller.
Upvotes: 0
Reputation: 1671
You could do it this way instead:
let alert = UIAlertController(title: "Alert", message: "Message.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { action in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
self.presentViewController(alert, animated: true, completion: nil)
Upvotes: 0