我需要增加genNum变量并将其传递给ForEach循环中的另一个结构。我的代码编译正确,但无法在模拟和画布中预览它。获取“无法预览此文件”。我收到的另一个错误是"RemoteHumanReadableError:操作无法完成。(BSServiceConnectionErrorDomain错误3.)“。
BSServiceConnectionErrorDomain (3):==BSErrorCodeDescription: OperationFailed
import SwiftUI
@available(iOS 14.0, *)
struct CategoryView: View {
@State var genNum: Int = -1
var categories: [Int: [PokemonData]] {
Dictionary(
grouping: pokemonData,
by: { $0.generation }
)
}
var columns: [GridItem] = [
GridItem(.fixed(170)),
GridItem(.fixed(170))
]
var body: some View {
NavigationView {
ScrollView {
LazyVGrid(columns: columns) {
ForEach(categories.keys.sorted(), id: \.self) { key in
CategoryCard(genNum: self.increment()) // <--- Having problem with this line
}
}
AllCard()
.padding(.horizontal, 15)
.padding(.bottom, 20)
}
.navigationTitle("Categories")
}
}
// Function to increment the state value
func increment() -> Int {
self.genNum += 1
let i = genNum
return i
}
}发布于 2020-08-12 15:04:07
如果您只想将值从0传递给CategoryCard()初始化程序,则可以使用enumerated()函数。该函数接受一个数组作为输入,并返回一个元组数组,其中第一个项是数组索引,第二个项是原始数组中的元素。
例如,此代码:
let array = ["zero", "one", "two", "three"]
array.enumerated().forEach { (index, string) in
print (index, string)
}产出如下:
0 zero
1 one
2 two
3 three这样您就可以像这样重写代码:
LazyVGrid(columns: columns) {
ForEach(categories.keys.sorted().enumerated(), id: \.self) { (index, key) in
CategoryCard(genNum: index) // <--- Having problem with this line
}
}(免责声明:我还没有使用SwiftUI,所以我不完全清楚ForEach在您的LazyGrid中正在做什么)
https://stackoverflow.com/questions/63378919
复制相似问题