presentViewController没有navigationController swift

时间:2016-11-02 15:38:38

标签: swift navigationcontroller presentviewcontroller

我转换到下一个视图是这样的:

if let navigationController = navigationController {
        if let storyboard:UIStoryboard = UIStoryboard(name: "myStoryboard", bundle: nil) {

            if let vc = storyboard.instantiateViewControllerWithIdentifier("myViewController") as? MyViewController {
                dispatch_async(dispatch_get_main_queue()) {
                    navigationController.presentViewController(vc, animated: true, completion: nil)
                }
            }
        }
    }

这很好用。我想要这种过渡。但是当我在MyViewController中调用以下代码时,NavigationController是nil:

if let navigationController = navigationController {
       print("yeah i have a nc")
    } else {
         print("its nil") //this will call
    }

当我使用navigationController.pushViewController(vc, animated: true) 时,一切正常。但我真的想要过渡。这是我的错误实现还是presentViewController总是没有navigationController?如果是,我该怎么办?

我的控制器A已经嵌入在navigationController中。我使用navigationController.presentViewController转到MyViewController。从MyViewController我想推送到下一个ViewController C。

1 个答案:

答案 0 :(得分:3)

为我工作的解决方案

我不知道为什么,但是当你使用presentViewController时,你必须为你的navigationController定义一个新的(?)根。

在这种情况下,我理解Ahmad Fs的答案。

if let storyboard:UIStoryboard = UIStoryboard(name: "myStoryboard", bundle: nil) {
        if let vc = storyboard.instantiateViewControllerWithIdentifier("MyViewController") as? MyViewController {
            if let navController:UINavigationController = UINavigationController(rootViewController: vc) {
                dispatch_async(dispatch_get_main_queue()) {
                    self.presentViewController(navController, animated:true, completion: nil)
                }
            }
        }
    }

SWIFT 3

    let storyboard = UIStoryboard(name: UIConstants.Storyboards.registration, bundle: nil)
    if let vc = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as? YourViewController {

        let navigationController = UINavigationController(rootViewController: vc)
        DispatchQueue.main.async {
            navigationController.present(vc, animated: true)
        }
    }

我找到了“我的”解决方案here