You will have to rely on a static variable. so change the @State to static.
I previously noticed that @State was not enough, cause it seems the main render cycle of @State. Consider my example that has one issue with it.
@State var canExecuteOnDisappear = false
modalContent
.zIndex(1)
.onAppear {
canExecuteOnDisappear = true
}
.onDisappear {
// HACK: onDisappear fires multiple times for some reason
if canExecuteOnDisappear {
print("CDM onDisappear")
canExecuteOnDisappear = false
}
}
if I were to go through 4 different types of modal content for each content in an array. presenting another sheet after dismissing the previous one I get the behavior:
("CDM onDisappear") gets printed 3 times just fine, and then the last time it prints out 3 instead of 1 so in total 7.
CDM onDisappear
CDM onDisappear
CDM onDisappear
CDM onDisappear
CDM onDisappear
CDM onDisappear
CDM onDisappear
So change that to a static variable so it updates immediately and not on the main thread.
- @State var canExecuteOnDisappear = false
+ static var canExecuteOnDisappear = false
this fixes this issue.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: