gpt4 book ai didi

scroll - 如何正确地将 "cell item"从 SwiftUI LazyVGrid 传递给 .sheet?

转载 作者:行者123 更新时间:2023-12-04 14:12:26 25 4
gpt4 key购买 nike

这是我的例子,我不知道这是否是一个错误。我所有的单元格都正确加载,但是当我尝试调出 DetailView() 时作为工作表,粘贴的项目始终是网格中首先显示的项目(在我这里的情况下位于左上角),而不是被点击的“单元格”。那么,为什么 ForEach 循环中的项目正确填充单元格,但没有通过按钮传递给 .sheet?

    import SwiftUI

let columnCount: Int = 11
let gridSpacing: CGFloat = 1

struct GridView: View {

@State var showingDetail = false

let data = (1...755).map { "\($0)" }
let columns: [GridItem] = Array(repeating: .init(.flexible(), spacing: gridSpacing), count: columnCount)
let colCount: CGFloat = CGFloat(columnCount)
var body: some View {
GeometryReader { geo in
ScrollView (showsIndicators: false) {
LazyVGrid(columns: columns, spacing: gridSpacing) {
ForEach(data, id: \.self) { item in

Button(action: {
self.showingDetail.toggle()
}) {
GridCell(item: item, size: (geo.size.width - (colCount * gridSpacing)) / colCount)
}.sheet(isPresented: $showingDetail) {
DetailView(item: item)
}
}
}
}
.padding(.horizontal, gridSpacing)
}
}
}

struct GridCell: View {
let isVault: Bool = false
let item: String
let size: CGFloat
var body: some View {
ZStack {
Rectangle()
.fill(Color.orange)
.cornerRadius(4)
Text(item)
.foregroundColor(.white)
.font(.system(size: size * 0.55))
}
.frame(height: size)
}
}

struct DetailView: View {

let item: String

var body: some View {
Text(item)
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
GridView()
.preferredColorScheme(.dark)
}
}

我错过了什么?另外,在我的 iPad pro 11 上滚动有点紧张,有没有人看到相同的行为?

最佳答案

在这种用例中,使用由项目构造的工作表的变体更合适,因为工作表必须从动态内容中移出(否则您创建的工作表与 ForEach 中的项目一样多)。
这是可能的解决方案。使用 Xcode 12/iOS 14 测试。

// helper extension because .sheet(item:...) requires item to be Identifiable
extension String: Identifiable {
public var id: String { self }
}

struct GridView: View {

@State private var selected: String? = nil

let data = (1...755).map { "\($0)" }
let columns: [GridItem] = Array(repeating: .init(.flexible(), spacing: gridSpacing), count: columnCount)
let colCount: CGFloat = CGFloat(columnCount)
var body: some View {
GeometryReader { geo in
ScrollView (showsIndicators: false) {
LazyVGrid(columns: columns, spacing: gridSpacing) {
ForEach(data, id: \.self) { item in

Button(action: {
selected = item // store selected item
}) {
GridCell(item: item, size: (geo.size.width - (colCount * gridSpacing)) / colCount)
}
}
}
}.sheet(item: $selected) { item in // activated on selected item
DetailView(item: item)
}
.padding(.horizontal, gridSpacing)
}
}
}

关于scroll - 如何正确地将 "cell item"从 SwiftUI LazyVGrid 传递给 .sheet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63217260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com