How do I set the toggle state in a foreach loop in SwiftUI

后端 未结 1 767
孤独总比滥情好
孤独总比滥情好 2021-01-14 06:34

When I try to set show a toggle inside a loop of value from a dictionary, I get very little help from the error message.

If I un-comment the 3 lines of commented co

相关标签:
1条回答
  • 2021-01-14 07:08

    The issue here is that the initializer Toggle(isOn:label:) takes a Binding<Bool> for its isOn parameter rather than just a Bool. A Binding<_> is sort of a readable-writable "view" into a property that allows a control to update a value that it doesn't own and have those changes propagate out to whoever does own the property.

    EDIT: I made this more complicated than it needed to be. The following works:

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

    By using a $propertyValues, we are accessing a Binding to the array itself, which is transformed into bindings to each of the elements.

    EDIT:

    For the above to work, you'll need to add .value in a couple places in the body so that you are referring to the actual values and not the bindings to the values.

    0 讨论(0)
提交回复
热议问题