SwiftUI修改列表元素Bool状态不生效、无法驱动背景色更新的解决
核心原因
- 自定义的
prayerTimesImages是结构体,属于值类型。ForEach遍历拿到的prayerIcon是原数组元素的临时拷贝,不是和@State管理的源数据联动的可写引用。 - 长按回调里对临时拷贝的属性修改,完全不会影响@State存储的原始数组,既无法持久化改动,也无法触发SwiftUI的视图重绘流程,因此打印结果始终是初始的false,背景色也不会发生变化。
修正实现
方法一:基于id定位索引修改原数组
保留原有遍历逻辑,仅调整长按回调的修改逻辑,通过元素id匹配到@State数组中的真实元素位置,直接更新对应位置的属性:
.onLongPressGesture(minimumDuration: 1) { // 匹配对应元素的UUID拿到数组中的准确索引 guard let index = prayerTimesImage.firstIndex(where: { $0.id == prayerIcon.id }) else { return } // 直接修改@State管理的原数组元素,触发状态刷新 prayerTimesImage[index].isActive = true print(prayerTimesImage[index].isActive) }
方法二:使用绑定驱动的ForEach遍历
更贴合SwiftUI单向数据流规范的写法,直接给ForEach传入绑定类型的数据源,让遍历过程中拿到的元素和原状态形成双向绑定,修改属性时会自动同步更新原数组:
// 替换原有值类型遍历的ForEach ForEach($prayerTimesImage) { $item in Button(action: {}) { HStack { Image(item.name) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 50, height: 50) Text("\(item.name)") Spacer() } .padding(.horizontal, 5) .padding(.vertical, 10) .background(item.isActive ? Color.green : Color.white) .onLongPressGesture(minimumDuration: 1) { // 直接修改绑定的属性即可同步原状态 item.isActive = true print(item.isActive) } } .cornerRadius(10) .shadow(radius: 2) }
提示:由于自定义模型已经遵循
Identifiable协议,传入绑定数组给ForEach时不需要额外指定id参数,SwiftUI会自动完成元素的身份识别。
内容的提问来源于stack exchange,提问作者Yonus
相关产品推荐
相关产品推荐

