首页 > 解决方案 > 如何从“ForEach”中只选择一个按钮?

问题描述

我有一些数据并完成了ForEach将它们写入按钮的操作。然后我有一个onLongPressGesture,我想在长按时更改特定按钮的背景颜色。我怎样才能实现它?

这是我的代码。

@State var selectedSummaryOption = "Daily"
    var hi = false
    var summaryOptions:[String] = ["Daily", "Weekly", "Monthly"]
    @State var prayerTimesImage = [
        prayerTimesImages(name: "Fajr", isActive: false),
        prayerTimesImages(name: "Zuhr", isActive: false),
        prayerTimesImages(name: "Asr", isActive: false),
        prayerTimesImages(name: "Maghrib", isActive: false),
        prayerTimesImages(name: "Isha", isActive: false)]
VStack {
                                    ForEach(prayerTimesImage, id: \.id) {prayerIcon in
                                        Button(action: {}) {
// HS -- Content of Button
                                            HStack {
                                                Image(prayerIcon.name)
                                                    .resizable()
                                                    .aspectRatio(contentMode: .fit)
                                                    .frame(width: 50, height: 50)
                                                Text("\(prayerIcon.name)")
                                                Spacer()
                                            }
                                            .padding(.horizontal, 5)
                                            .padding(.vertical, 10)
                                            .background(prayerIcon.isActive ? Color.green : Color.white)
                                            //.scaleEffect(longPressed ? 0.98 : 1)
                                            .onLongPressGesture(minimumDuration: 1) {
                                                prayerIcon.isActive = true   //gives error
                                                print(prayerIcon.isActive)
                                            }
                                            
                                        }.cornerRadius(10)
                                        .shadow(radius: 2)}
                                        .font(.system(.headline))
                                        .foregroundColor(.black)
                            }
                        }.frame(width: totalWidth, alignment: .center)

标签: swiftswiftuigesture

解决方案


prayerIcon是一个副本,这就是你得到错误的原因。用于enumerated在状态属性容器中同时拥有索引和项目并直接更改模型,例如

ForEach(Array(prayerTimesImage.enumerated()), id: \.1.id) { (index, prayerIcon) in

     ...

    .onLongPressGesture(minimumDuration: 1) {
        prayerTimesImage[index].isActive = true   // << change in model
    }
}

推荐阅读