SwiftUI 中的 @Binding 和 ForEach [英] @Binding and ForEach in SwiftUI

查看:23
本文介绍了SwiftUI 中的 @Binding 和 ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解如何在 SwiftUI 中将 @BindingForEach 结合使用.假设我想从布尔数组中创建一个 Toggle 列表.

I can't undertand how to use @Binding in combination with ForEach in SwiftUI. Let's say I want to create a list of Toggles from an array of booleans.

struct ContentView: View {
    @State private var boolArr = [false, false, true, true, false]

    var body: some View {
        List {
            ForEach(boolArr, id: .self) { boolVal in
                Toggle(isOn: $boolVal) {
                    Text("Is (boolVal ? "On":"Off")")
                }                
            }
        }
    }
}

我不知道如何将数组内布尔值的绑定传递给每个 Toggle.上面的代码给出了这个错误:

I don't know how to pass a binding to the bools inside the array to each Toggle. The code here above gives this error:

使用未解析的标识符$boolVal"

Use of unresolved identifier '$boolVal'

好吧,这对我来说很好(当然).我试过了:

And ok, this is fine to me (of course). I tried:

struct ContentView: View {
    @State private var boolArr = [false, false, true, true, false]

    var body: some View {
        List {
            ForEach($boolArr, id: .self) { boolVal in
                Toggle(isOn: boolVal) {
                    Text("Is (boolVal ? "On":"Off")")
                }                
            }
        }
    }
} 

这次的错误是:

'ForEach' 上的引用初始值设定项 'init(_:id:content:)' 需要'Binding' 符合 'Hashable'

Referencing initializer 'init(_:id:content:)' on 'ForEach' requires that 'Binding' conform to 'Hashable'

有没有办法解决这个问题?

Is there a way to solve this issue?

推荐答案

您可以使用类似下面的代码.请注意,您将收到已弃用的警告,但要解决此问题,请查看其他答案:https://stackoverflow.com/a/57333200/7786555

You can use something like the code below. Note that you will get a deprecated warning, but to address that, check this other answer: https://stackoverflow.com/a/57333200/7786555

import SwiftUI

struct ContentView: View {
    @State private var boolArr = [false, false, true, true, false]

    var body: some View {
        List {
            ForEach(boolArr.indices) { idx in
                Toggle(isOn: self.$boolArr[idx]) {
                    Text("boolVar = (self.boolArr[idx] ? "ON":"OFF")")
                }
            }
        }
    }
}

这篇关于SwiftUI 中的 @Binding 和 ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆