Search code examples
swiftlistswiftuiview

<SwiftUI> Passing references between views when using lists with @Binding


I'm a newbie in SwiftUI programming and having a basic question.
Wondering why the value in "selectedIndex" in this example is not reflected in the child view, "TestChildView". How can I modify this so that I can get the correct selectedIndex value in the child view?

import SwiftUI

struct TestView: View {
    @State var selectedIndex: Int = 0
    var body: some View {
        NavigationStack {
            VStack {
                List {
                    Section(header:Text("Test")) {
                        ForEach(0 ..< 5, id: \.self) {selectedIndex in
                            NavigationLink {
                                TestChildView(selectedIndex: $selectedIndex)
                            } label: {
                                Text(String(selectedIndex)
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}
struct TestChildView: View {
    @Binding var selectedIndex: Int
    var body: some View {
        VStack {
            Text(String(selectedIndex))
        }
        
    }
}

Solution

  • Currently the @State var selectedIndex ... and the selectedIndex in the ForEach loop are two different things. That is why it is not reflected in the child view, TestChildView.

    To ...get the correct selectedIndex value in the child view, remove the

    @State var selectedIndex: Int = 0 
    

    and the $ in the call of TestChildView and use

    TestChildView(selectedIndex: selectedIndex)
    

    Also use let selectedIndex: Int in TestChildView

    EDIT-1:

    here is the full test code I use to show it works well for me.

     import SwiftUI
    
     @main
     struct TestApp: App {
         var body: some Scene {
             WindowGroup {
                 ContentView()
             }
         }
     }
    
    struct TestView: View {
        
        var body: some View {
            NavigationStack {
                VStack {
                    List {
                        Section(header:Text("Test")) {
                            ForEach(0..<5, id: \.self) { selectedIndex in
                                NavigationLink {
                                    TestChildView(selectedIndex: selectedIndex)
                                } label: {
                                    Text(String(selectedIndex))
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    struct TestChildView: View {
        let selectedIndex: Int
        
        var body: some View {
            VStack {
                Text(String(selectedIndex))
            }
        }
    }
    
    
    struct ContentView: View {
        var body: some View {
            TestView()
        }
    }