First item in a List is always selected

In this scenario we can pass clicked item like baton from ForEach to Alert to FullScreen to Details. And, of course, we should move corresponding modifiers out of cycle, they don’t need to be applied to each row.

Here is a modified code. Tested with Xcode 12.1 / iOS 14.1.

struct ContentView: View {
    var array: [Object] = [Object(id: .init(),property: 1),Object(id: .init(),property: 2),Object(id: .init(),property: 3)]
    
    @State var alertItem: Object?
    @State var selectedItem: Object?
    
    
    var body: some View {
        NavigationView{
            List{
                ForEach(array){ item in
                    VStack{
                        Text(String(item.property))
                    }.onTapGesture(){ self.alertItem = item}
                }
            }
              .alert(item: $alertItem) { item in
                    Alert(title: Text("show details view?"), message: Text(""),
                            primaryButton: .default (Text("Show")) {
                              selectedItem = item
                            },
                            secondaryButton: .cancel()
                    )
              }
              .fullScreenCover(item: $selectedItem){ DetailsView(property: $0.property) }
        }
    }
}

Leave a Comment