且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 SwiftUI 元素绑定到字典中的值?

更新时间:2022-01-22 02:18:46

我设法通过为每个过滤器使用自定义绑定来实现工作.

I managed to make is work by using a custom binding for each filter.

final class ExternalData: BindableObject {
    let didChange = PassthroughSubject<Void, Never>()

    var filters: Dictionary<String, Bool> = [:] {
        didSet {
            didChange.send(())
        }
    }

    init() {
        filters["Juniper"] = true
        filters["Beans"] = false
    }

    var keys: [String] {
        return Array(filters.keys)
    }

    func binding(for key: String) -> Binding<Bool> {
        return Binding(getValue: {
            return self.filters[key] ?? false
        }, setValue: {
            self.filters[key] = $0
        })
    }
}

keys 属性将 filters 键列为 String 以便可以显示(使用 ForEach(externalData.keys))

The keys property list the filters keys as String so that it can be displayed (using ForEach(externalData.keys))

binding(for:) 方法,为给定的键创建一个自定义的Binding.此绑定被赋予 Toggle 以读取/写入包装字典中的当前值.

The binding(for:) method, create a custom Binding for the given key. This binding is given to the Toggle to read/write the current value in the wrapped dictionary.

查看代码:

struct ExampleView : View {

    @EnvironmentObject var externalData : ExternalData

    var body: some View {
        VStack {
            ForEach(externalData.keys) { key in
                Toggle(isOn: self.externalData.binding(for: key)) {
                    Text(key)
                }
            }
        }
    }
}