简体   繁体   中英

swiftUI tabView how to set default view onAppear?

I have a tabView with several views, and I would like to know how to undefine a default view when loading it. By default, Xcode assigns the first view but I want the second view to be loaded when the application is launched.

var body: some Scene {
    WindowGroup {
        TabView {
            alertView()
            todayView()
            forecastView()
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))
        .onAppear
        {
            UIPageControl.appearance().currentPageIndicatorTintColor = .black
            UIPageControl.appearance().pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.2)
        }
    }
}

Let's move everything in explicit scene root view

var body: some Scene {
    WindowGroup {
      ContentView()
    }
}

And now we can use selection for this, like

struct ContentView: View {
  @State private var selection = 2   // << here !!

  var body: some View {
        TabView(selection: $selection) {   // << here !!
            alertView().tag(1)        
            todayView().tag(2)             // << here !!
            forecastView().tag(3)
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))
        .onAppear
        {
            UIPageControl.appearance().currentPageIndicatorTintColor = .black
            UIPageControl.appearance().pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.2)
        }
  }
}

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