我正在尝试创建自己的网格,它可以调整每个元素的大小。没关系。这是一个代码
GeometryReader { geo in
let columnCount = Int((geo.size.width / 250).rounded(.down))
let tr = CDNresponse.data?.first?.translations ?? []
let rowsCount = (CGFloat(tr.count) / CGFloat(columnCount)).rounded(.up)
LazyVStack {
ForEach(0..<Int(rowsCount), id: \.self) { row in // create number of rows
HStack {
ForEach(0..<columnCount, id: \.self) { column in // create columns
let index = row * columnCount + column
if index < (tr.count) {
VStack {
MovieCellView(index: index, tr: tr, qualities: $qualities)
}
}
}
}
}
}
}
但由于我不知道元素的确切数量及其索引,我需要在视图中计算它们。
let index = row * columnCount + column
这就是问题所在 - 如果我MovieCellView(index: index ... )
在索引更改时像往常一样传递它们 ( ),则新值不会传递给视图。我不能使用@State 和@Binding,因为我不能直接在 View Builder 中声明它,也不能在 struct 上声明它,因为我不知道计数。如何正确传递数据?
代码MovieCellView
:
struct MovieCellView: View {
@State var index: Int
@State var tr: [String]
@State var showError: Bool = false
@State var detailed: Bool = false
@Binding var qualities: [String : [Int : URL]]
var body: some View {
...
}
}
最简单的示例
刚刚在 VStack 中添加Text("\(index)")
了 MovieCellView 和Text("\(index)")
在MovieCellView
正文中。VStack 中的索引总是在变化,但在 MovieCellView 中没有。
有必要澄清一下,我的应用程序在 macOS 上并且窗口已调整大小