Considering the simplest possible tab view app in SwiftUI:
struct ContentView: View {
@State private var selection = 0
var body: some View {
TabView(selection: $selection){
Text("First View")
.font(.title)
.tabItem {
VStack {
Image("first")
Text("First")
}
}
.tag(0)
Text("Second View")
.font(.title)
.tabItem {
VStack {
Image("second")
Text("Second")
}
}
.tag(1)
}
}
}
Whenever a tab is tapped, the tab items are reloaded and you have the opportunity to change the image for a selected tab if you needed by comparing the selection with the tag. However, if you have a dynamic number of tabs in a variable and use a ForEach
to display them, that doesn't work:
struct ContentView: View {
@State private var selection = 0
private var items: [AnyView] {
return [
AnyView(Text("First View")
.font(.title)
.tabItem {
VStack {
Image("first1")
Text("First1")
}
}
.tag(0)),
AnyView(Text("Second View")
.font(.title)
.tabItem {
VStack {
Image("second")
Text("Second")
}
}
.tag(1))
]
}
var body: some View {
TabView(selection: $selection){
ForEach(0..<self.items.count) { index in
self.items[index]
}
}
}
}
The body of the ForEach
is not called when the view reloads. Is there a way to accomplish changing an image while also using a ForEach
in your TabView?