我想在我的SwiftUI应用首次启动时启动一个教程。该代码应在项目中的什么位置以及如何在首次启动应用程序时启动只是SwiftUI View的教程?
我已经知道如何在使用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
}
答案 0 :(得分:0)
尝试将其放入您的sceneDelegate
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()
}
答案 1 :(得分:0)
在 SwiftUI 2.0 之后的 SampleApp
中:
import SwiftUI
@main
struct SampleApp: App {
@AppStorage("didLaunchBefore") var didLaunchBefore: Bool = true
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
if didLaunchBefore {
SplashView()
} else {
ContentView()
}
}
}
}
然后在 SplashView
中添加一个具有如下操作的按钮:
UserDefaults.standard.set(false, forKey: "didLaunchBefore")