Nathan Liu
Nathan Liu

Reputation: 284

Changing TabView(selection:) via @Published variable

I have a tab view with tagged items.

struct ContentView: View {
@ObservedObject var tabController = TabController()

var body: some View {
    TabView(selection: $tabController.selectedTab) {

        HomeView()
            .tabItem{
                Image(systemName: "house.fill")
                    .font(.system(size: 20))

                Text("Home")
        }.tag(0)

        ...
}

I have an ObservableObject that has a @Published selectedTab variable and a function to change it.

When I call the function, it correctly prints the index of the tab I want to switch to, but the tab does not switch. Does anyone know why?

class TabController: ObservableObject {
    @Published var selectedTab = 3

    func changeTab(tabIndex: Int) {
        self.selectedTab = tabIndex
        print(selectedTab)
    }
}

Instead of changeTab(tabIndex:) I have also tried directly changing selectedTab.

Edit: I am calling the changeTab(tabIndex:) like this:

struct DetailsView: View {
    @ObservedObject var tabController = TabController()

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 0) {

                  Button(action: {self.tabController.changeTab(tabIndex: 2)}) {
                      HStack {
                          Image(systemName: "bubble.left.fill")
                              .buttonIconModifier()
                          Text("Switch Tab")
                      }
                  }.modifier(ButtonStyle())
             }
         }        
    }
}

Upvotes: 4

Views: 756

Answers (1)

Asperi
Asperi

Reputation: 258491

Here is a mistake

struct ContentView: View {
@ObservedObject var tabController = TabController() // << 1st controller

and

struct DetailsView: View {
    @ObservedObject var tabController = TabController() // << 2nd controller

your views use different instances - DetailsView change 2nd, but ContentView listen for 1st.

They need to use one instance. I asked how they relates, because the fix is to pass tabController from one to another, or share via EnvironmentObject.

Upvotes: 2

Related Questions