Hello, can someone please explain to me how does SwiftUI TabView works "under the hood" , I don't understand why do all views in TabView get reinitialized each time I switch between tabs. Xcode Version 15.3, iOS 16+
Below is the code snippet :
struct ScreenOne: View {
init() {
print("ScreenOne init called !")
}
var body: some View {
Text("This is screen one!")
}
}
struct ScreenTwo: View {
init() {
print("ScreenTwo init called !")
}
var body: some View {
Text("This is screen two !")
}
}
struct TabViewTest: View {
@State var selectedIndex: Int = 1
var body: some View {
TabView(selection: $selectedIndex) {
ScreenOne()
.tag(1)
.tabItem {
Text("Item 1")
}
ScreenTwo()
.tag(2)
.tabItem {
Text("Item 2")
}
}
// .onChange(of: selectedIndex) { oldValue, newValue in
//
// }
// NOTE: When code above is uncommented
// Screen one & Screen two initializers get called
// each time switch to different tab occurs
}
}
Snippet output with the commented out code :
- App loads
- Both print statements get called -> "ScreenOne init called ! & "ScreenTwo init called !
- Switch between taps
- Nothing happens
Snippet output with the uncommented code :
- App loads
- Both print statements get called -> ScreenOne init called ! & ScreenTwo init called !
- Switch between taps
- Both print statements get called -> ScreenOne init called ! & ScreenTwo init called !
@eskimo heeelp :) Thanks in advance !