为什么 ForEach 不能在 SwiftUI 中正确使用 onTapGesture 修饰符

Why does ForEach not work with onTapGesture modifier correctly in SwiftUI

我想弄清楚为什么当仅点击一个元素时 ForEach 数组中的所有元素都会发生变化。

import SwiftUI

struct SwiftUIView: View {
    
    @State var boolTest = false
    
    var nums = ["1","2","3","4","5","6","7"]
    
    var body: some View {
        VStack {
            ForEach(nums, id: \.self) { num in
                Text("\(num)")
                    .font(.system(size: 70))
                    .foregroundColor(boolTest ? .red : .green)
                    .onTapGesture {
                        boolTest.toggle()
                    }
            }
            
        }
    }
}

例如,当我点击包含 1 的视图时,所有其他数字也会改变颜色。我希望能够点击一个数字并且只有那个数字改变颜色。

您正在为数组的所有元素使用一个变量 nums。因此,前景颜色将始终相同 - 它们都读取相同的值。

你需要的是创建一个独立管理自己颜色的子视图。将 ForEach 与其内容分开,如下所示:

struct SwiftUIView: View {
    
    // This variable should not be here: all elements read the same value
    // @State var boolTest = false
    
    var nums = ["1","2","3","4","5","6","7"]
    
    var body: some View {
        VStack {
            ForEach(nums, id: \.self) { num in

                // Call another view
                Subview(text: num)
            }
            
        }
    }
}

// Create a subview with its own variable for each element
struct Subview: View {

    // Here, there is one boolTest for each element
    @State private var boolTest = false
    let text: String

    var body: some View {
                Text(text)
                    .font(.system(size: 70))
                    .foregroundColor(boolTest ? .red : .green)
                    .onTapGesture {
                        boolTest.toggle()
                    }
    }
}