swift - ForEach loop with state

元气小坏坏 提交于 2021-01-29 07:10:48

问题


If I have this code:

@State var n = 3
var body: some View {
    VStack {
        Button(action:{
            if self.n == 3 {
                self.n = 5
            } else {
                self.n = 3
            }
        }) {
            Text("Click me")
        }
        ForEach(1..<self.n+1) { i in
            Text(String(i))
        }
    }
}

I expect this code to toggle between 1 2 3 and 1 2 3 4 5 on the screen when you click the button, however it only shows 1 2 3. How would I fix this?


回答1:


The form of ForEach that you have used is fine if the number of items is constant, but if the Views might change, then you need to either provide items that conform to the protocol Identifiable, or use the form of ForEach that provides the id::

ForEach(1..<self.n+1, id: \.self) { i in
    Text(String(i))
}

The value passed as id is a KeyPath that tells SwiftUI which property of the item to use as its identifier. In the case of an Int, you can just use the Int's value which can be accessed through the .self property.

SwiftUI uses the identifiers to know when items in the ForEach have been added or removed, thus it needs them for you to be able to see the change.



来源:https://stackoverflow.com/questions/63144836/swift-foreach-loop-with-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!