SwiftUI 优化
SwiftUI Optimization
以下代码编译需要一些时间,不知是否有人可以优化一下。我是 SwiftUI 的新手,所以请不要用那个代码来评判我
以下代码生成一个 VStacks(cells) 网格;我工作了,但速度很慢,我不想等待那么长且未经优化的代码,这样的代码通常不是一个好的解决方案。
如果我在 ForEach 循环中使用固定数字,代码编译速度很快,但在我当前的设置下编译速度很慢...
let paletteColumns = 4 // The amount of columns
let tmpCt = 18 // The amount of cells in total
VStack {
ForEach (0..<(tmpCt / paletteColumns) + 1) {
row in
HStack {
ForEach (0..<min(tmpCt-(row * paletteColumns), paletteColumns)) {
col in
VStack {
// CODE FOR EACH CELL
}
}
}
}
}
所以我通过将第二个 ForEach 的内容放入专用函数来解决我的问题。
更新代码:
func Whatever(row: Int) -> Int {
return min(tmpCt-(row * paletteColumns), paletteColumns)
}
let paletteColumns = 4 // The amount of columns
let tmpCt = 18 // The amount of cells in total
VStack {
ForEach (0..<(tmpCt / paletteColumns) + 1) {
row in
HStack {
ForEach (0..<Whatever()) {
col in
VStack {
// CODE FOR EACH CELL
}
}
}
}
}
PS: 答案未标记为已回答,因为我必须等待 2 天才能接受自己的答案
以下代码编译需要一些时间,不知是否有人可以优化一下。我是 SwiftUI 的新手,所以请不要用那个代码来评判我
以下代码生成一个 VStacks(cells) 网格;我工作了,但速度很慢,我不想等待那么长且未经优化的代码,这样的代码通常不是一个好的解决方案。
如果我在 ForEach 循环中使用固定数字,代码编译速度很快,但在我当前的设置下编译速度很慢...
let paletteColumns = 4 // The amount of columns
let tmpCt = 18 // The amount of cells in total
VStack {
ForEach (0..<(tmpCt / paletteColumns) + 1) {
row in
HStack {
ForEach (0..<min(tmpCt-(row * paletteColumns), paletteColumns)) {
col in
VStack {
// CODE FOR EACH CELL
}
}
}
}
}
所以我通过将第二个 ForEach 的内容放入专用函数来解决我的问题。
更新代码:
func Whatever(row: Int) -> Int {
return min(tmpCt-(row * paletteColumns), paletteColumns)
}
let paletteColumns = 4 // The amount of columns
let tmpCt = 18 // The amount of cells in total
VStack {
ForEach (0..<(tmpCt / paletteColumns) + 1) {
row in
HStack {
ForEach (0..<Whatever()) {
col in
VStack {
// CODE FOR EACH CELL
}
}
}
}
}
PS: 答案未标记为已回答,因为我必须等待 2 天才能接受自己的答案