如何在SwiftUI的ForEach循环中增加状态?

问题描述

我需要增加 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
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)