【问题标题】:SwiftUI custom nested array ForEachSwiftUI 自定义嵌套数组 ForEach
【发布时间】:2021-11-15 01:18:43
【问题描述】:

所以我有一个模型的嵌套数组:

let models = [[ButtonModel]]
    struct ButtonModel: Identifiable {
        let id = UUID()
        let value: String
        let style: ColorStyle
        
        init(_ value: String, _ style: ColorStyle) {
            self.value = value
            self.style = style
        }
    }

然后我想将其添加为网格,因此我有一个 VStack,我在其中循环 x 数量的 HStacks,其中包含按钮。

但由于某种原因,我得到了这个错误:

无法将类型“[[ButtonModel]]”的值转换为预期的参数类型“Binding”

无法推断通用参数“C”

VStack {
    ForEach(viewModel.buttons, id: \.self) { buttons in
                HStack(spacing: GridPoints.x2) {
                    Spacer()
                    ForEach(buttons) { buttonValue in
                        if buttonValue == "/" {
                            imageButton(for: Asset.Image) { viewModel.addValue(buttonValue) }
                        } else {
                            Button(buttonValue, action: { viewModel.addValue(buttonValue) })
                                .buttonStyle(customFont: .h3)
                                .background(Color.backgroundColor)
                                .styleText(style: TextStyle.h3)
                        }
                    }
                    Spacer()
                }
                .padding(GridPoints.x1)
            }
    }

有人知道这个错误是什么吗?

【问题讨论】:

标签: arrays foreach swiftui


【解决方案1】:

编辑

看来您在使用buttonValue 时也犯了错误。

你应该这样使用它

ForEach(buttons) { button in
    if button.value == "/" {
        imageButton(for: Asset.Image) { viewModel.addValue(button.value) }
    }
    ...
}

ForEach 需要一个数组,其每个元素都是Identifiable(或使用id: \.something 来判断要使用哪个id)。

您的问题是,如果您使用数组数组,这意味着外部数组的每个元素都是另一个数组,符合Identifiable

另一方面,如果您使用ForEach(arrayOfArray, id: \.self),则说明标识符将是外部数组中必须符合Hashable 的每个元素。 Array 符合 Hashable 如果其元素符合。所以尝试将你的结构更改为

struct ButtonModel: Identifiable, Hashable { ... }

替代解决方案

您可以将结构更改为

struct ButtonsGroup: Identifiable {
    let id = UUID()
    let buttons: [ButtonModel]
}

那么你将像这样使用它:

let groups = [ButtonsGroup]()

ForEach(groups) { group in
    ForEach(group.buttons) { button in
        Text(button.value)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-07
    • 2012-09-24
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多