ForEach中的工作表不会在项目SwiftUI上循环 [英] Sheet inside ForEach doesn't loop over items SwiftUI

查看:166
本文介绍了ForEach中的工作表不会在项目SwiftUI上循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ForEach内使用工作表时遇到问题.基本上,我有一个列表,其中显示了数组中的许多项目,还有一个触发工作表的图像.问题在于,当显示我的工作表时,它仅显示我数组的第一项,即哈利·波特"(Harry Potter).在这种情况下.

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 sheet is presented it only shows the first item of my array which is "Harry Potter" in this case.

这是代码

struct ContentView: View {
    @State private var showingSheet = false
    
    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.showingSheet = true
                    }
                    .sheet(isPresented: self.$showingSheet) {
                        Text(self.movies[movie])
                    }
                }
            }
        }
    }
}

推荐答案

应该只有一张图纸,因此这里是可行的方法-使用另一张图纸修改器并通过选择激活它

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

已通过Xcode 12/iOS 14(与iOS 13兼容)进行了测试

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])
            }
        }
    }
}

这篇关于ForEach中的工作表不会在项目SwiftUI上循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆