You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI实时列表更新时滑动删除选中行偏移问题求助

问题解决思路

问题根源

你当前用数组索引(indices)作为ForEach的标识,当新通知加入数组时,索引会重新排序,导致滑动操作绑定的视图和实际数据错位,出现选中行跳转的问题。索引是不稳定的标识,数组元素变化时它会跟着改变,这才是界面错乱的核心原因。

解决方案

放弃用索引遍历,直接遍历通知数组,用每个通知的唯一id作为ForEach的标识(确保你的通知模型有唯一id字段)。这样每个列表项的标识是固定的,不会因为数组元素增减而改变,从根源避免视图错位。

修改后的代码示例

List {
    // 直接遍历数组元素,用元素的id作为唯一标识
    ForEach(scanViewModel.notificationList, id: \.id) { notification in
        NotificationRow(
            date: notification.date,
            message: notification.message,
            mid: notification.mid,
            appeared: notification.appeared
        )
        .listRowSeparator(.hidden)
        .listRowBackground(Color.BG)
        .listRowInsets(.init(top: 10, leading: 10, bottom: 10, trailing: 20))
        .swipeActions(allowsFullSwipe: false) {
            Button {
                // 直接用当前通知的id,无需依赖索引
                indexID = notification.id
                islastDeletAlertShow = true
            } label: {
                Label("Delete", systemImage: "trash.fill")
            }
            .tint(Color.customRed)
        }
    }
}

额外优化建议

如果你的通知模型还没遵循Identifiable协议,建议让它遵循,这样ForEach可以省略id: \.id参数,代码更简洁:

struct Notification: Identifiable {
    let id: String // 或者UUID,确保唯一
    let date: Date
    let message: String
    let mid: String
    let appeared: Bool
    // 其他字段
}

之后ForEach可以简化为:

ForEach(scanViewModel.notificationList) { notification in
    // ... 内容不变
}

内容的提问来源于stack exchange,提问作者Furkan Tümay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 05:00:07