2

Is it possible to add UIAlert view inside UIAlertAction ?

Because when I tried to add UIAlert view inside UIAlertAction, it says

"Warning: Attempt to present on whose view is not in the window hierarchy!"

Here's my code.

let myAlert = UIAlertController(title: "Title", message: "title here", preferredStyle: UIAlertControllerStyle.alert)
let okaction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler:
    {
        action in
        let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let navigationController = UINavigationController.init(rootViewController: myViewController)
        appDelegate.window?.rootViewController = navigationController
        appDelegate.window?.makeKeyAndVisible()

        if (statement here == 1) {
            let myAlert = UIAlertController(title: "Title", message: "title", preferredStyle: UIAlertControllerStyle.alert)
            myAlert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
            self.present(myAlert, animated: true, completion: nil)
            return
        }
    }
)
myAlert.addAction(okaction)
self.present(myAlert, animated: true, completion: nil)
4

2 回答 2

2

Try to present AlertController on navigationController.

Changed line

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

With

navigationController.present(myAlert, animated: true, completion: nil)
于 2017-04-05T09:26:36.533 回答
0

Try wrapping your call to the second alert in a function then call that function.

Like this.

let myAlert = UIAlertController(title: "Title", message: "title here", preferredStyle: UIAlertControllerStyle.alert)
let okaction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: { action in

    let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let navigationController = UINavigationController.init(rootViewController: myViewController)
    appDelegate.window?.rootViewController = navigationController
    appDelegate.window?.makeKeyAndVisible()

    if (statement here == 1) {
        self.callAlert()
    }
})

myAlert.addAction(okaction)
self.present(myAlert, animated: true, completion: nil)

func callAlert() {
    let myAlert = UIAlertController(title: "Title", message: "title", preferredStyle: UIAlertControllerStyle.alert)
    myAlert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
    self.present(myAlert, animated: true, completion: nil)
}
于 2017-04-05T09:25:32.523 回答