首页 > 解决方案 > 如何使用 SwiftUI 在首次应用启动时启动教程?

问题描述

我想在我的 SwiftUI 应用程序首次启动时启动一个教程。这段代码应该在项目中的什么位置以及如何在应用程序首次启动时启动教程,它只是一个 SwiftUI 视图?

我已经知道如何在使用 UserDefaults 之前检查应用程序是否已启动。我想知道如何启动 SwiftUI 视图,然后在用户完成教程后如何启动标准 ContentView。

let hasLaunchedBefore = UserDefaults.standard.bool(forKey: "hasLaunchedBefore")

if hasLaunchedBefore {
     // Not first launch
     // Load ContentView here
} else {
     // Is first launch
     // Load tutorial SwiftUI view here
     UserDefaults.standard.set(true, forKey: "hasLaunchedBefore") // Set hasLaunchedBefore key to true
}

标签: swiftui

解决方案


试着把它放在你的场景中

let hasLaunchedBefore = UserDefaults.standard.bool(forKey: "hasLaunchedBefore")
let content = ContentView()
let tutorial = TutorialView()
if let windowScene = scene as? UIWindowScene {
      let window = UIWindow(windowScene: windowScene)
       if hasLaunchedBefore {
           window.rootViewController = UIHostingController(rootView: content)
       } else {
           window.rootViewController = UIHostingController(rootView: tutorial)
           UserDefaults.standard.set(true, forKey: "hasLaunchedBefore") 
       }
        self.window = window
        window.makeKeyAndVisible()
}

推荐阅读