问题
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