I have a basic SwiftUI app where the profile view can be accessed in two ways: through the navigation link in view 1, and through the second tab. When I go to profile view via tab 0’s navigation link the onAppear method executes once as expected and the function is called. But if I now switch to tab 1, the new profile view is displayed but the onAppear function executes twice, once for the newly displayed profile view and once for the old profile view in tab 0. The onAppear executes twice every time in this order: New profile view tab 1, then, old profile view tab 0. I’m not sure why this happens but I was able to almost get ride of the issue by just allowing the function to be called every 1 second via a bool flag. And since the unwanted onAppear always executes second the function doesn’t get called because the bool is false. This isn’t a good solution though.
import SwiftUI
struct mainTab: View {
@State var tab: Int = 0
var body: some View {
VStack {
if tab == 0 {
NavigationStack {
SwiftUIView1()
}
} else if tab == 1 {
NavigationStack {
profileView()
}
}
HStack {
Button {
tab = 0
} label: {
Text("tab 0")
}
Button {
tab = 1
} label: {
Text("tab 1")
}
}
}
}
}
struct SwiftUIView1: View {
var body: some View {
NavigationStack {
ScrollView {
NavigationLink {
profileView()
} label: {
Text("Hello")
}
}
}
}
}
struct profileView: View {
var body: some View {
ZStack {
Text("Some View")
}
.onAppear {
//executes twice
//first executes for the top view
//second executes again for
runSomething()
}
}
func runSomething(){
}
}




