【问题标题】:swiftui 2.0 Image Gallery onTapgesture only shows the first image in the arrayswiftui 2.0 图片库 onTapgesture 只显示数组中的第一张图片
【发布时间】:2021-02-24 02:00:47
【问题描述】:

我正在为一个应用程序创建一个可重复使用的图库视图,并且在点击任何图片时遇到困难,它假设变成全屏,但无论点击什么图片,每次都只显示数组中的第一张图片。下面是我的代码,谢谢。

导入 SwiftUI

struct ReusableGalleryView: 查看 { 让 greenappData: GreenAppNews

let gridLayout: [GridItem] = Array(repeating: GridItem(.flexible()), count: 3)

@State private var fullscreen = false
@State private var isPresented = false

var body: some View {
    VStack{

            ScrollView{
                LazyVGrid(columns: gridLayout, spacing: 3) {
                    ForEach(greenappData.GreenAppGallery, id: \.self) { item in
                        Image(item)
                          .resizable()
                            .frame(width: UIScreen.main.bounds.width/3, height: 150)
                            .onTapGesture {
                                self.isPresented.toggle()
                                print(" tapping number")
                                      }
                            .fullScreenCover(isPresented: $isPresented) {
                                FullScreenModalView( imageFiller: item)
                            }
                          .background(Color.gray.opacity(0.5))
                    }
                }
                .padding(.horizontal)
            }
    }
}

}

这是一个json数据的例子:

{ “id”:“1”, “GreenAppGallery”:[ “图片1”, “图片2”, “图3”, “图4”, “图片5”, “图6”, “图7”, “图8”, “图9”, “图 10” ] },

【问题讨论】:

标签: swiftui image-gallery


【解决方案1】:

fullScreenCoversheet 一样,在 iOS 14 中使用 isPresented: 时往往会产生这种类型的行为。

要修复它,您可以更改为fullScreenCover(item: ) 表单。

没有您的所有代码,我无法为您提供其外观的确切版本,但要点是:

  1. 删除您的 isPresented 变量
  2. 将其替换为可选的presentedItem 变量。可能是您画廊中的数据类型。请注意,它必须符合 Identifiable(这意味着它必须具有 id 属性)。
  3. 不是切换isPresented,而是将presentedItem 设置为item
  4. 使用 fullScreenCover(item: ) { presentedItem in FullScreenModalView( imageFiller: presentedItem) } 并将您的 presentedItem 变量传递给它
  5. 移动fullScreenCover,使其附加到ForEach 循环而不是Image

使用此系统,您应该会看到它对正确的项目做出响应。

这是我的另一个答案,其中包含 sheet@State var not updated as expected in LazyVGrid

【讨论】:

  • 我按照您的指示尝试了它没有工作,我不知道它是否允许在 stackoverflow 上通过电子邮件对应,以便我可以将我的代码发送给您以便更好地了解我的问题?
  • 最好在这里创建一个最小的可重现示例
猜你喜欢
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多