单击alertView中的按钮时如何导航ViewController

时间:2016-02-08 06:13:23

标签: swift swift2

根据下面的代码,当我点击“接受”按钮时,它不会导航到SecondViewController,它只会显示黑屏。任何帮助表示赞赏。

   let alertController = UIAlertController(title: tit!, message: "Book Now!", preferredStyle: .Alert)
   let declineAction = UIAlertAction(title: "Decline", style: .Cancel, handler: nil)
   alertController.addAction(declineAction)

   let acceptAction = UIAlertAction(title: "Accept", style: .Default) { (_) -> Void in
        let nv=SecondViewController()
        self.presentViewController(nv, animated:true, completion:nil)
    }
   presentViewController(alertController, animated: true, completion: nil)
   alertController.addAction(acceptAction)

2 个答案:

答案 0 :(得分:1)

要打开任何UIViewController只需要instantiate它。你正在做的只是创建类的对象。

这样做:

let nv = self.storyboard!.instantiateViewControllerWithIdentifier("storyboardidentifier") as! SecondViewController
self.presentViewController(nv, animated:true, completion:nil)

这是您想要的UIViewController

答案 1 :(得分:0)

创建从当前视图控制器到SecondViewController的segue链接,并在故事板中为其指定标识符,您可以使用以下代码

    let alert = UIAlertController(title: "Options", message: "Book Now!", preferredStyle: .Alert)

    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
    alert.addAction(UIAlertAction(title: "Accept", style: UIAlertActionStyle.Default, handler: { (alertAction) -> Void in
        self.performSegueWithIdentifier("FirstToSecond", sender: self)

    }))
    self.presentViewController(alert, animated: true, completion: nil)

注意:您的第一个视图控制器将成为锚点。

如果您已将SecondViewController嵌入导航控制器并且还想传递该值,则可以添加以下内容

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "FirstToSecond" {
        let nav = segue.destinationViewController as! UINavigationController
        let svc = nav.viewControllers[0] as! SecondViewController
        //svc.delegate = self //uncomment this if you need to set a delegate as well
        svc.value = ""
    }
}

这是使用xCode 7&斯威夫特2.希望这有助于:)