【问题标题】:How to navigate ViewController when clicking button in alertView单击 alertView 中的按钮时如何导航 ViewController
【发布时间】:2016-05-17 17:55:07
【问题描述】:

鉴于下面的代码,当我单击“接受”按钮时,它不会导航到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)

【问题讨论】:

    标签: swift swift2


    【解决方案1】:

    要打开任何UIViewController 必须instantiate 它。而你所做的只是创建类的对象。

    这样做:

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

    这是打开你的UIViewController 随意!

    【讨论】:

    • storyboardidentifier 表示 mystoryboard 名称。是否正确
    • @Honestraj19 确保您已从StoryBoard 为您的UIViewController 提供“标识符”
    【解决方案2】:

    创建一个从当前视图控制器到 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 和 Swift 2。希望这会有所帮助 :)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2011-04-18
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多