简体   繁体   中英

How to show a SwiftUI View programmatically without a button

I have a problem right now: What I want: The first time the app starts my already existing view should be presented. I already implemented something in the AppDelegate that checks if the app launched for the first time. And if thats the case another view should be presented. Is there a method to do this directly in the AppDelegate like it was possible with Storyboards?

Thank you in advance.

In your AppDelegate you have a hosting controller that bootstraps the main SwiftUI view. So one way to achieve this is to conditionally set the rootView .

UIHostingController(rootView: isFirstTime ? FirstTimeView() : ContentView())

I would create an initial RootView that merely switches between content and provides an EnvironmentValues that's passed to it.

struct RootView: View {
  @Environment(\.isInitialLaunch) var isInitialLaunch: Bool

  var body: some View {
    Group {
      if isInitialLaunch {
        FirstTimeView()
      } else {
        ContentView()
      }
  }
}

Then, in SceneDelegate :

self.window?.rootViewController = UIHostingController(rootView: RootView().environment(\.isInitialLaunch, isInitialLaunch))

Or, make isInitialLaunch a @State (or @Binding , @ObservedObject , etc.) variable. This way, after your onboarding process, if you change it to false , SwiftUI will actually automatically animate users to the ContentView .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM