SwiftUI - 使用 'pushViewController' 时出现 fatal error

标签 swift uiviewcontroller uinavigationcontroller swiftui pushviewcontroller

因为 SwiftUI 有一个令人窒息的导航系统,我试图在我的 SwiftUI View 中使用 pushViewController

但是,当我运行代码并按下按钮时,出现以下错误 -

Fatal error: Unexpectedly found nil while unwrapping an Optional value:
file /Users/.../Conjugate/Conjugate/Pages/Practice/PracticeView.swift, line 93

这是我的代码-

PracticeView.swift

...
Button(action: {    
             /* Line 93 */ UIApplication.shared.windows[0].rootViewController?.navigationController!.pushViewController(UIHostingController(rootView: ResultView()), animated: true)
}) { ... }
...

SceneDelegate.swift

...
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)

        let nonEmbeddedViewController = UIHostingController(rootView: PracticeView(verb: verbData.shuffled(), numberOfQuestions: CGFloat(verbData.count)))
        let navigationController = UINavigationController(rootViewController: nonEmbeddedViewController)

        window.rootViewController = navigationController

        self.window = window
        window.makeKeyAndVisible()
    }
}
...

有人知道怎么解决吗?我怀疑 navigationController 在展开时的值为 nil,但我不知道解决方案。谢谢!

编辑 - 澄清

我正在尝试制作一款教育应用程序,针对特定主题对您进行测验。 “练习 View ”是用户回答问题的地方,每次他们按下右下角的按钮(我在问题中提到的那个)时,这些问题都会被替换。但是,当所有问题都已回答后,按钮需要打开另一个 View (“结果 View ”),而不是仅仅切换当前 View 中的文本。此外,导航栏必须隐藏在练习 View 和结果 View 中,而模态表则不行。如果您需要引用,我猜是 Duolingo 或 this slideshow可能会有用。

最佳答案

代码 Markdown 可能会帮助你。忽略 SwiftUI 导航 View ,使用需要显示 (a) 练习 View (带有一系列问题)或 (b) 结果的模型。如果您设置模型:

@Published var currentQuestion:Question
@Published var showResults:Bool

(这是非常的伪代码!)

您实际上可以拥有一个(简单的)内容 View (同样是伪代码),即:

struct ContentView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        if model.showResults {
            ShowResults()
        } else {
            ShowCurrentQuestion()
        }
    }
}

ShowResultsShowCurrentQuestionViews。你可以在两者之间做各种动画(默认是淡入/淡出),绝对不需要“导航”。只要您的模型驱动 ContentView,它就可以工作。

是的,我不是在谈论 NavigationView - 虽然我在 UINavigationController 方面是“老派”,但我正在开发的 SwiftUI 应用程序并没有”不需要任何类似于 push/pop 或 segues 的东西。但是......我正在使用我刚才描述的东西。)

关于SwiftUI - 使用 'pushViewController' 时出现 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57470237/

相关文章:

swift - 使用 swift 将工具栏按钮移至工具栏左侧

iphone - UIPageViewController 与 UIViewControllerInteractiveTransitioning

ios - 将 rootViewController 从 uiviewcontroller 更改为 uinavigationcontroller

ios - 单击按钮时隐藏 TabBar 并显示 NavigationController 工具栏

ios - UINavigationController 做事务时发生崩溃

ios - 如何检查 HealthKit 是否被授权

ios - 在 swift 3 中,每次在我的提要中点赞帖子时,如何执行动画?

ios - 如何在 Swift 中设置代理?

ios - UINavigationController popViewControllerAnimated 缓慢过渡

ios - 如何调用 navigationControllerPreferredInterfaceOrientationForPresentation