swift - ForEach loop with state
问题 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