【问题标题】:UINavigationController is nil in swift 3UINavigationController 在swift 3中为零
【发布时间】:2017-11-22 05:30:48
【问题描述】:

在我的主故事板中,我有 1 个导航控制器和后续的 swift 文件 NavigationCtr.swift。

viewController 在不同的xib中。

现在我想从 NavigationCtr 类中推送我的 viewController。

       let vcFirst = FirstViewController(nibName: "FirstViewController", bundle: nil)
    self.navigationController!.pushViewController(vcFirst, animated: true)

我遇到了一个异常

致命错误:在展开可选值时意外发现 nil

所以当我尝试从 viewDidLoad 打印时

   print(self.navigationController)

在 NavigationCtr.swift 类中它给出了 nil。所以没有任何效果


我在目标 C 中创建了一个新项目,它运行良好。 附上故事板图片 高度赞赏直接方向的任何提示。 注意:-我是 swift 新手

【问题讨论】:

  • 请说明您是如何在代码中从“NavigationCtr”推送 ViewController。
  • 在您的图像中,它只显示 NavigationCtr ViewController 并且它被设置为入口点。所以看起来你没有添加 NavigationController。你需要选择ViewController,选择Edit -> Embed In -> Navigation Controller。
  • 从情节提要中我删除了 ViewController 并放置了一个 navigationController。所以这个想法是主故事板将只有 navigationController 和 ViewCtr 将在不同的 xibs
  • 为什么情节提要只有navigationController?照@totiG 所说的去做;在storyboard中创建一个ViewController,选中它,然后点击Editor -> Embed in -> Navigation Controller

标签: ios swift uinavigationcontroller storyboard


【解决方案1】:

主要问题是使用 self.navigationController

由于我的故事板只有 navigationController 我应该只使用 self 关键字。 如下

let vcFirst = FirstViewController(nibName: "FirstViewController", bundle: nil)
self.pushViewController(vcFirst, animated: true)

【讨论】:

    【解决方案2】:

    对于第一个控制器,将其设置为rootController,而不是推送(显示)。

    self.navigationController = UINavigationController(rootViewController: vcFirst)
    

    或者设置它的视图控制器

    self.navigationController = UINavigationController()
    navigationController.setViewControllers([vcfirst], animated: true)
    

    【讨论】:

    • self.navigationCONtroller 是一个只读属性 @property(nullable, nonatomic,readonly,strong) UINavigationController *navigationController;
    • 是的,你不能这样设置导航控制器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多