如何在iOS 9的alert.addAction中按下OK时打开另一个视图控制器

时间:2015-11-15 22:09:55

标签: ios swift

我想显示一个名为InViewController的viewcontroller,当" OK"从add.alertAction开始按下。

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){}
}

3 个答案:

答案 0 :(得分:3)

当你添加一个completionHandler来添加它时,你可以将它添加到UIAlertAction中,如下所示:

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){}
}

要设置StoryboardID,您可以在 Identity Inspector 中使用Interface Builder,请参阅下图:

enter image description here

我将上述代码中的所有内容引用到ViewControllerA,您必须根据需要设置UIViewController的名称。

修改

您指向StoryBoard上的UIView或其他对象。按下UIViewController其他对象顶部的黄色指示符,如下图所示:

enter image description here

我希望这对你有所帮助。

答案 1 :(得分: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)

答案 2 :(得分:0)

以下是如何做到的, 我只是更新Victor Sigler的优秀作品

你通过这个小小的更新来回答他的答案。

 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) {}
}