Home > Software design >  swiftUI tabView how to set default view onAppear?
swiftUI tabView how to set default view onAppear?

Time:08-09

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)
        }
    }
}

CodePudding user response:

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)
        }
  }
}
  • Related