【问题标题】:Swift - Present another view controller with its navigation barSwift - 展示另一个带有导航栏的视图控制器
【发布时间】:2016-07-09 10:42:47
【问题描述】:

我有两个 ViewController——一个带有情节提要,一个没有。这两个视图控制器在顶部都有自己的导航栏。现在,当我使用 self.presentViewController(editorViewController, animated: true, completion: nil) 时,我的 editorViewController 会出现,但没有导航栏。

任何想法如何解决这个问题?

【问题讨论】:

标签: ios swift viewcontroller navigationbar


【解决方案1】:

我使用以下代码解决了这个问题:

let editorViewController = IMGLYMainEditorViewController()
let navEditorViewController: UINavigationController = UINavigationController(rootViewController: editorViewController)
self.presentViewController(navEditorViewController, animated: true, completion: nil)

我刚刚添加了navEditorViewController,因为它使我的导航栏及其项目出现。

【讨论】:

  • 但是呈现的 UIViewController 没有返回按钮。如何处理?
  • @zulkarnainshah 当你展示一个新的导航控制器时,你之前的导航堆栈会被删除。如果你需要显示返回按钮,那么你必须展示视图控制器,而不是导航控制器。
【解决方案2】:

试试self.navigationController!.pushViewController(...)

【讨论】:

  • 可能是因为您没有使用导航控制器。你能告诉我你的故事板吗?
  • 这是我的故事板postimg.org/image/5x0bszdlf,当我按下编辑时,应该会弹出图像编辑器 editorViewController
  • 对不起,如果我坚持.. 所以你的故事板只有那个视图控制器??
  • 我认为你应该使用 NavigationController。看这里:postimg.org/image/byfh6263r
【解决方案3】:

Swift 5+

let destinationNavigationController = self.storyboard!.instantiateViewController(withIdentifier: "nav") as! UINavigationController
destinationNavigationController.modalPresentationStyle = .fullScreen        
self.present(destinationNavigationController, animated: true, completion: nil)

在这里,您的导航栏将替换为新的导航栏。

【讨论】:

    【解决方案4】:

    鉴于我们已经有 UINavigationController 而不是当前的,所以对于仍然对这个问题感到好奇的每个人:

    斯威夫特 3

    首先,我们需要找到我们要呈现的UIViewController

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let destinationViewController = storyboard.instantiateViewController(withIdentifier: "DestinationViewController") as! DestinationViewController
    

    接下来,我们为 UINavigationController 做同样的事情:

    let destinationNavigationController = storyboard.instantiateViewController(withIdentifier: "DestinationNavigationController") as! UINavigationController
    

    然后,我们要将 DestinationViewController 带到目标 UINavigationController 堆栈的顶部:

    destinationNavigationController.pushViewController(destinationViewController, animated: true)
    

    最后,只介绍目的地UINavigationController

    self.present(destinationNavigationController, animated: true, completion: nil)
    

    【讨论】: