Sheet inside ForEach doesn't loop over items SwiftUI

后端 未结 2 856
猫巷女王i
猫巷女王i 2020-12-07 02:58

I have an issue using a sheet inside a ForEach. Basically I have a List that shows many items in my array and an image that trigger the sheet. The problem is that when my sh

2条回答
  •  天命终不由人
    2020-12-07 03:46

    There should be only one sheet, so here is possible approach - use another sheet modifier and activate it by selection

    Tested with Xcode 12 / iOS 14 (iOS 13 compatible)

    extension Int: Identifiable {
        public var id: Int { self }
    }
    
    struct ContentView: View {
        @State private var selectedMovie: Int? = nil
    
        var movies = ["Harry potter", "Mad Max", "Oblivion", "Memento"]
        var body: some View {
            NavigationView {
                List {
                    ForEach(0 ..< movies.count) { movie in
                        HStack {
                            Text(self.movies[movie])
                            Image(systemName: "heart")
                        }
                            .onTapGesture {
                                self.selectedMovie = movie
                        }
                    }
                }
                .sheet(item: self.$selectedMovie) {
                    Text(self.movies[$0])
                }
            }
        }
    }
    

提交回复
热议问题