Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing TabView(selection:) via @Published variable

Tags:

swift

swiftui

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())
             }
         }        
    }
}
like image 673
Nathan Liu Avatar asked Oct 18 '25 12:10

Nathan Liu


1 Answers

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.

like image 142
Asperi Avatar answered Oct 20 '25 03:10

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!