【问题标题】:How do I set the toggle state in a foreach loop in SwiftUI如何在 SwiftUI 的 foreach 循环中设置切换状态
【发布时间】:2019-06-16 03:52:04
【问题描述】:

当我尝试在字典的值循环内设置显示切换时,我从错误消息中得到的帮助很少。

如果我取消注释下面的 3 行注释代码,尝试为循环中的每个属性添加切换,我会收到以下错误:

无法将 'HStack, Text, ConditionalContent)>>' 类型的值转换为闭包结果类型 '_'

import SwiftUI

struct properties {
    var id : Int
    var property : String
    var isOn : Bool
}

struct ContentView: View {

    @State var propertyValues: [properties] = [properties(id: 1, property: "DemoData", isOn: true),
                                                 properties(id: 2, property: "ShowLocalEvents", isOn: false)]

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(propertyValues.identified(by: \.id)) { propertyValue in
                        HStack {
//                            Toggle(isOn: propertyValue.isOn) {
//                                Text("")
//                            }
                            Text("\(propertyValue.property)")
                            if propertyValue.isOn {
                                Text("On")
                            } else {
                                Text("Off")
                            }
                        }
                    }
                }
            }
        }
    }
}

【问题讨论】:

    标签: binding toggle swiftui


    【解决方案1】:

    这里的问题是初始化器Toggle(isOn:label:)Binding<Bool> 用作其isOn 参数,而不仅仅是BoolBinding<_> 是一种对属性的可读可写“视图”,它允许控件更新它不拥有的值并将这些更改传播给确实拥有该属性的任何人.

    编辑:我把它弄得比它需要的更复杂。以下作品:

    ForEach($propertyValues.identified(by: \.id.value)) { (propertyValue: Binding<properties>) in
        HStack {
            Toggle(isOn: propertyValue.isOn) {
                Text("")
            }
            // ...
        }
    }
    

    通过使用$propertyValues,我们将Binding 访问到数组本身,该数组被转换为每个元素的绑定。

    编辑:

    要使上述操作生效,您需要在正文的几个位置添加.value,以便您指的是实际值,而不是值的绑定。

    【讨论】:

    • 感谢对绑定的补充和关于价值的评论。现在运行良好。
    • 但是我怎样才能访问 propertyValue.property?前任。 ForEach($propertyValues.identified(by: \.id.value)) { (propertyValue: Binding&lt;properties&gt;) in HStack { Toggle(isOn: propertyValue.isOn) { Text(propertyValue.property) } // ... } }
    • @user1366265 你应该可以访问propertyValue.property.value
    • @Jumhyn 我还在为此苦苦挣扎,我得到“无法在当前上下文中推断闭包类型”ForEach ($thisCardData, id: \.self) { (card: Binding&lt;ICard&gt;) in thisCardData 是可识别的 [ICard] 类型,所以我不确定我是否需要 id: ForEach 语句的一部分。
    • 我确实收到此错误...通用结构“ForEach”要求“Binding”符合“RandomAccessCollection”。那是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2023-03-25
    • 2014-10-04
    • 2021-10-13
    • 1970-01-01
    相关资源
    最近更新 更多