ForEach(0 ... 5,id:\ .self){n--“ n”的范围是什么?

请参阅以下TestView。当我单击“按钮5”时,我看到警报显示“ 单击按钮0 ”。

struct TestView: View {
   @State var showAlert = false
   var body: some View {
      VStack {
         ForEach(0...5,id: \.self) { n in
            Button(action: {
               self.showAlert.toggle()
            }) {
               Text("Button \(n)")
            }
            .padding(20)
            .border(Color.green,width: 4)
            .padding(8)
            .alert(isPresented: self.$showAlert) {
               Alert(title: Text("Button \(n) clicked"))
            }
         }
      }
   }
}

无论我单击哪个按钮,警报始终显示“单击了按钮0” 。我期望每个按钮应该显示自己的按钮索引。想知道为什么吗?

qw12c 回答:ForEach(0 ... 5,id:\ .self){n--“ n”的范围是什么?

我怀疑这种情况正在发生,因为在状态变量更改时,TestView中的所有内容都会重新呈现。因此,您的警报仅针对第一次循环迭代显示。决定更改其他变量,该变量应包含单击的按钮索引:

struct TextView: View {
    @State var showAlert = false
    @State var clickedButtonIndex = 0
    var body: some View {
       VStack {
          ForEach(0...5,id: \.self) { n in
             Button(action: {
                self.showAlert.toggle()
                self.clickedButtonIndex = n
             }) {
                Text("Button \(n)")
             }
             .padding(20)
             .border(Color.green,width: 4)
             .padding(8)
             .alert(isPresented: self.$showAlert) {
                Alert(title: Text("Button \(self.clickedButtonIndex) clicked"))
             }
          }
       }
    }
}

您将得到以下结果: enter image description here

本文链接:https://www.f2er.com/3169589.html

大家都在问