Reputation: 1298
OK something weird is going on and I want to see if anyone else have this issue.
Consider the following ViewModel
class with one published property to use from a View:
final class ViewModel: ObservableObject {
@Published var isActive = false
}
When using this view:
struct MainView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
NavigationView {
Form {
NavigationLink (
destination: ChildView(isActive: $viewModel.isActive),
isActive: $viewModel.isActive,
label: { Text("Go to child view") }
)
// Adding this ForEach causes the NavigationLink above to have a broken binding
ForEach(1..<4) {
Text("\($0)")
}
}
.navigationBarTitle("Test")
}
}
}
And this SubView:
struct ChildView: View {
@Binding var isActive: Bool
var body: some View {
Button("Go back", action: { isActive = false })
}
}
The expected result is when tapping on "Go to child view", navigating to the subview and tapping "Go back" to return to the main view - it should navigate back using the isActive
binding.
But actually, the button "Go Back" Doesn't work.
BUT If I remove the ForEach
element from the form in the main view, the button works again. And it looks like the ForEach
breaks everything.
Form
to VStack
fixes the issue@State
also fixes the issueForEach
to a subview fixes the issue but as soon as I pass the viewmodel or part of it to the subview as a binding or as a ObservedObject - it still brokenCan anything advise if there is a logical issue with the code or is it a SwiftUI bug? Any suggestions for a workaround?
https://i.sstatic.net/BaggK.gif
Apple developer forum discussion: https://developer.apple.com/forums/thread/674127
It looks like the issue has been fixed in the latest iOS 14.5 Beta 2 🎉
Upvotes: 1
Views: 549