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

SwiftUI视图如何按时间顺序显示数据并维持@Binding绑定?

解决SwiftUI绑定排序日期列表的问题

核心思路

直接对@Binding数组排序会生成新数组,无法直接关联原绑定。需要通过标识匹配找到原数组中对应的元素,再获取绑定,同时保留排序后的展示顺序。

前提条件

确保DatesInfo遵循Identifiable协议(或拥有唯一id属性),这样能准确匹配原数组中的元素:

struct DatesInfo: Identifiable {
    let id = UUID()
    var date: Date
    // 其他属性...
}

修正后的代码

struct DatesView: View {
    @Binding var dates: [DatesInfo]
    
    // 生成排序后的日期数组(按日期升序,可根据需求改为降序)
    private var sortedDates: [DatesInfo] {
        dates.sorted { $0.date < $1.date }
    }
    
    var body: some View {
        List {
            ForEach(sortedDates) { sortedDate in
                // 通过id匹配原数组中的索引,获取绑定
                if let index = dates.firstIndex(where: { $0.id == sortedDate.id }) {
                    CardView(thisDate: dates[index])
                        .background(
                            NavigationLink("", destination: DetailView(thisDate: $dates[index]))
                                .opacity(0)
                        )
                }
            }
            .onDelete(perform: delete)
        }
    }
    
    // 实现删除逻辑
    private func delete(at offsets: IndexSet) {
        // 注意:offsets是排序后列表的索引,需要转换为原数组的索引
        let sortedIndices = offsets.map { sortedDates[$0].id }
        dates.removeAll { sortedIndices.contains($0.id) }
    }
}

关键说明

  • 排序处理:通过计算属性sortedDates对原绑定数组排序,不修改原数组的存储顺序,只调整展示顺序。
  • 绑定匹配:利用firstIndex(where:)通过id找到原数组中对应的元素,从而获取$dates[index]的绑定,确保导航链接能正确修改原数据。
  • 删除适配:删除时,先将排序后列表的偏移量转换为原数组的元素id,再从原数组中移除对应元素,避免索引不匹配的问题。

内容的提问来源于stack exchange,提问作者Laura Edwards

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:40:04