Sheet inside ForEach doesn't loop over items SwiftUI

后端 未结 2 849
猫巷女王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:21

    I changed your code to have only one sheet and have the selected movie in one variable.

    extension String: Identifiable {
        public var id: String { self }
    }
    
    struct ContentView: View {
        @State private var selectedMovie: String? = nil
        
        var movies = ["Harry potter", "Mad Max", "Oblivion", "Memento"]
        var body: some View {
            NavigationView {
                List {
                    ForEach(movies) { movie in
                        HStack {
                            Text(movie)
                            Image(systemName: "heart")
                        }
                        .onTapGesture {
                            self.selectedMovie = movie
                        }
                    }
                }
                .sheet(item: self.$selectedMovie, content: { selectedMovie in
                    Text(selectedMovie)
                })
            }
        }
    }
    
    0 讨论(0)
  • 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])
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题