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

SwiftUI中如何将列表项从升/降序恢复至默认排序?

SwiftUI 恢复列表默认排序的解决方案

你当前的问题出在直接修改了@State修饰的items数组——每次排序都会覆盖原始顺序,自然没法恢复默认。而且你else分支里的排序逻辑return lhs.name == rhs.name是错误的,这个条件无法还原原始顺序,只会让数组排序混乱。

正确的做法是保留原始数据源的副本,通过状态变量控制排序模式,根据模式返回对应排序后的数组,而不是直接修改原数组。

具体实现步骤:

  1. 定义排序类型枚举(比用Int更清晰)
enum SortType: Int {
    case `default` = 0
    case ascending = 1
    case descending = 2
}
  1. 分离原始数据和状态变量
    把原始数据存为常量(不修改),用状态变量管理当前排序模式:
// 原始数据源,始终保留初始顺序
let originalItems: [Names] = itemsName
// 控制当前排序类型的状态变量
@State private var currentSortType: SortType = .default
  1. 用计算属性返回排序后的数组
    根据当前排序模式,动态返回对应的数组:
private var sortedItems: [Names] {
    switch currentSortType {
    case .default:
        return originalItems // 直接返回原始顺序
    case .ascending:
        return originalItems.sorted { $0.name < $1.name }
    case .descending:
        return originalItems.sorted { $0.name > $1.name }
    }
}
  1. 修改视图和排序逻辑
    在ForEach里使用计算属性sortedItems,并更新onChange的逻辑:
ForEach(sortedItems) { item in 
    NavigationLink(destination: FormulasView()) {
        VStack {
            NameRowView(items: item)
        }
    }
}
.onChange(of: sortListItems) { _ in
    if sortListItems == 1 {
        currentSortType = .ascending
    } else if sortListItems == 2 {
        currentSortType = .descending
    } else {
        currentSortType = .default
    }
}

为什么要这么做?

  • 原始数据始终保留,切换到默认排序时直接返回即可
  • 计算属性只会在排序模式变化时重新计算,性能高效
  • 避免了直接修改@State数组导致的状态混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:54:58