swift - 如何从“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)
解决方案
这prayerIcon
是一个副本,这就是你得到错误的原因。用于enumerated
在状态属性容器中同时拥有索引和项目并直接更改模型,例如
ForEach(Array(prayerTimesImage.enumerated()), id: \.1.id) { (index, prayerIcon) in
...
.onLongPressGesture(minimumDuration: 1) {
prayerTimesImage[index].isActive = true // << change in model
}
}
推荐阅读
- android - Viewpager inside recyclerView dissapears when scrolling up or down
- c++ - 使用填充构造函数初始化向量的向量
- javascript - 在一个功能中加载图像
- elasticsearch - 聚合是否可以将所有分组文档中的数组属性的所有值合并到合并文档中?
- javascript - JavaScript scroll() event endless loop when page scrolled to the bottom
- python - 将 Spark DataFrame 的架构转换为另一个 DataFrame
- python - 从噪声图像中提取数字
- angular - 在 ionic 5 或 Angular 应用程序中显示 HTML 内容中的图像
- centos - 指定 Arch 时 Repodiff 不能按预期工作的任何原因?
- python - 为什么我在使用 pip 的 docker 中遇到 SSL 问题