How to add Tab into SwiftUI App?
What is Tab?
Tab makes user can switch screens without navigation stack.
How to add Tab?
To add Tabs into your app, you should use TabView.
Then you can see Tabs like this
How to change icon for Tab?
If you want to add icon to your TabItems like this.
Just add Image into your TabItem.
You can use only Image, Text or both. Other components will be ignored.
But you can’t change the order of them.
You can also use Label instead them. I guess it is possible because Label has Image/Text.
How to know which TabItem is selected?
To listen a selected Tab Item, it is required to define State first.
@State private var selectedTabIndex = 0
And inject State variable to TabView
TabView(selection: $selectedTabIndex) {
You might think selectedTabIndex will be changed to 0,1,2 when select tabs
However selectedTabIndex is not changed.
We should specify tag like this.
You can also specify String values as tag.
But you should make variable to String.
If you want to run some codes when State variable, use onChange like this.
You can see the logs when selecting the Tabs.
onChange selected tab has been changed. index[1]onChange selected tab has been changed. index[2]onChange selected tab has been changed. index[1]onChange selected tab has been changed. index[0]