I recently ran into an issue while building an app with SwiftUI where I had a
TabView
that contained some views that modified their state in an onAppear
block. I'm still not sure why, but this caused some strange behavior in that
tapping on a tab would immediately return the user to the previous tab, but
tapping on the tab a second time would load correctly. Searching for solutions
to the problem got me nowhere, but I was able to work around this by making the
state changes outside of the TabView
's children and passing in the final state
I wanted in the constructors, but this of course didn't scale and tightly
coupled my child views with the TabView
. Just today, I stumbled upon a snippet
of code that gave the TabView
a Binding
variable for the tab selection
instead of letting it manage that state internally, and sure enough that solved
my issue. You just have to tag the child views with the same data type as the
selection variable, like so:
@State tabViewSelection: Int = 0
TabView(selection: $tabViewSelection) {
Child()
.tabItem { … }
.tag(0)
Child()
.tabItem { … }
.tag(1)
}
Here's the git commit in my own project where I fixed the issue. If you know of a better way to handle this, please let me know!