There are a few questions that mention this warning, but no general solutions or simple examples.
The following code has a main view and a subview with a text field. When clicking the “return” button on the subview, the following warning shows up:
Publishing changes from within view updates is not allowed, this will cause undefined behavior.
struct MainView: View {
@State var showSubView = true
var body: some View {
ZStack {
if showSubView {
SubView(showSubView: $showSubView)
}
}
}
}
struct SubView: View {
@Binding var showSubView: Bool
@State var text: String
var body: some View {
VStack {
TextField("", text: $text) // Removing this line removes the warning
Button("Return") {
showSubView = false
}
}
}
}
The odd part is that when the TextView
is removed, this warning doesn’t happen, even though text
is not linked to MainView
. Why is this error happening? Why does adding a TextView
cause it?