SwiftUI TabView and tag()

Created At: 2023-01-31 23:26:50 Updated At: 2023-01-31 23:30:23

Inside TabView you can put as many views as you want. TabView put item horizontally. In general you will see the first one. That’s the default set up. 

But you can change it. To change it you may declare a State variable at the top and then assign tag() function for each view inside the TabView. 

What’s tag() function? 

It’s a function that produces value(hashable) which could be used to keep track of your view specially with TabView. There are other cases where you can use tag().

After that if your State variable matches with tag() function value, then that certain TabView would be the first one. In that case it would ignore the default view order to show.

But if your State variable value and tag() value don’t match then, it would go back to the default order meaning that, you will see the first view on the screen that you put in the TabView().

So to control which view to show on the screen, you may declare a State variable and that variable value should match tag() function value.

So now we can take it one step further, TabView could work with Button view and bind them together as you tap using tag() function and State variable value. 

State variable value could be changed as you tap on the Button and that changed value could match the value of tag() inside TabView. This is how you may also create a custom TabBar in SwiftUI.


Add Reviews

Latest Posts

Subscribe our newsletter