【发布时间】:2021-08-09 07:58:56
【问题描述】:
我正在尝试创建自己的网格,它可以调整每个元素的大小。没关系。这是一个代码
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 {
...
}
}
最简单的例子
刚刚在带有 MovieCellView 的 VStack 中添加了 Text("\(index)"),在 MovieCellView 正文中添加了 Text("\(index)")。 VStack 中的索引总是在变化,但在 MovieCellView 中没有。
有必要澄清一下,我的应用程序是在 macOS 上并且窗口已调整大小
【问题讨论】:
标签: swift swiftui swiftui-view