ForEach 内的工作表不会遍历项目 SwiftUI [英] Sheet inside ForEach doesn't loop over items SwiftUI

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

问题描述

我在 ForEach 中使用工作表时遇到问题.基本上我有一个列表,它显示了我的数组中的许多项目和一个触发工作表的图像.问题是,当我的工作表出现时,它只显示我的数组的第一项,即哈利波特".在这种情况下.

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天全站免登陆