我有一些数据并做了一个 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)
答案 0 :(得分:2)
prayerIcon
是一个副本,这就是您收到错误的原因。使用 enumerated
在状态属性容器中直接拥有索引和项目以及更改模型,例如
ForEach(Array(prayerTimesImage.enumerated()), id: \.1.id) { (index, prayerIcon) in
...
.onLongPressGesture(minimumDuration: 1) {
prayerTimesImage[index].isActive = true // << change in model
}
}