Is it possible to recreate tabview item when you click on it. For example if I am on tabitem1, then click tabitem2, then go back to tabitem1, I want tabitem1 to be recreated. Can I do that in SwiftUI?
Asked
Active
Viewed 396 times
1 Answers
3
Here is an example how to reload all Views when changing the active TabBar Item. You use selection parameter in TabView and then use that selection inside your ContentView to make it reload whenever the selection changes.
struct ContentView: View {
@State var selection = 0
var body: some View {
TabView(selection: $selection) {
DefaultView(string: "First")
.tag(0)
.tabItem {
Image(systemName: "list.dash")
Text("Menu")
}
.id(UUID())
DefaultView(string: "Second")
.tag(1)
.tabItem {
Image(systemName: "square.and.pencil")
Text("Order")
}
}
.id(selection == 0 ? UUID() : UUID()) //<< here is selection used to make the view reload
}
}
If you check init()
method on DefaultView(), you will see it's getting called on every selection change.

davidev
- 7,694
- 5
- 21
- 56
-
Great answer davidev, that saved my live! What I don't clearly understand is the purpose of .id(selection == 0 ? UUID() : UUID()). Wouldn't it be cleaner to say .id(UUID()) ? – Matias Masso Jan 19 '21 at 17:51