Stasel
Stasel

Reputation: 1298

SwiftUI View with StateObject, a Form element and a ForEach breaks bindings when trying to use NavigationLink Inside the form

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 issue

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.

Additional findings:

  1. Changing Form to VStack fixes the issue
  2. Using a struct and a @State also fixes the issue
  3. Extracting the ForEach 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 broken

Can anything advise if there is a logical issue with the code or is it a SwiftUI bug? Any suggestions for a workaround?

Video of the expected behavior:

https://i.sstatic.net/BaggK.gif

Apple developer forum discussion: https://developer.apple.com/forums/thread/674127

Update

It looks like the issue has been fixed in the latest iOS 14.5 Beta 2 🎉

Upvotes: 1

Views: 549

Answers (1)

Stasel
Stasel

Reputation: 1298

The issue has been fixed on iOS 14.5

Upvotes: 0

Related Questions