問題描述
在 iOS 9 的 alert.addAction 中按下 OK 時如何打開另一個視圖控制器 (How to open another view controller when OK is pressed in alert.addAction in iOS 9)
當按下 add.alertAction
中的“OK”時,我想顯示一個名為 InViewController 的視圖控制器。
if ((user) != nil) {
let alert = UIAlertController(title: "Success", message: "Logged In", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
## 參考解法 #### 方法 1:
You can add a completionHandler to the UIAlertAction
when you add it to do it what you want, like in the following way:
if ((user) != nil) {
let alert = UIAlertController(title: "Success", message: "Logged In", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default, handler: { _ ‑> Void in
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("ViewControllerA") as! ViewControllerA
self.presentViewController(nextViewController, animated: true, completion: nil)
})
alert.addAction(OKAction)
self.presentViewController(alert, animated: true){}
}
To set the StoryboardID
you can use Interface Builder in the Identity Inspector, see the following picture:
I put everything in the above code referencing ViewControllerA
, you have to set the name of your UIViewController
according what you want.
EDIT:
You are pointing to a UIView
or some other object on the StoryBoard. Press the yellow indicator on top of the other objects which is your UIViewController
, like in the following picture:
I hope this help you.
方法 2:
let alert = UIAlertController(title: "Success", message: "Logged In", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default) { (action) ‑> Void in
let viewControllerYouWantToPresent = self.storyboard?.instantiateViewControllerWithIdentifier("SomeViewControllerIdentifier")
self.presentViewController(viewControllerYouWantToPresent!, animated: true, completion: nil)
}
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
方法 3:
Here's how you can do that , I'm just updating the good work of Victor Sigler
you follow his answer with this little update ..
private func alertUser( alertTitle title: String, alertMessage message: String )
{
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let actionTaken = UIAlertAction(title: "Success", style: .default) { (hand) in
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let destinationVC = storyBoard.instantiateViewController(withIdentifier: "IntroPage") as? StarterViewController
self.present(destinationVC!, animated: true, completion: nil)
}
alert.addAction(actionTaken)
self.present(alert, animated: true) {}
}
(by John Holliday、Victor Sigler、André Slotta、Harvester Haidar)