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

SwiftUI层级Table仅根元素可排序,子项排序失效求助

问题原因

你当前的代码仅对根层级的fileTree数组执行了排序,没有递归处理每个节点的children子数组,所以子项不会响应排序操作。SwiftUI的Table组件不会自动递归排序嵌套的子节点,需要手动遍历整个树结构完成全层级排序。

解决方案

添加一个递归排序函数,遍历所有节点并对每个层级的子数组应用排序规则:

  1. 新增递归排序函数
    在TableView结构体中添加以下私有函数:
private func sortFileTree(_ files: inout [File], using sortOrder: [KeyPathComparator<File>]) {
    // 排序当前层级的节点
    files.sort(using: sortOrder)
    // 递归排序每个节点的子节点
    for index in files.indices {
        guard var children = files[index].children else { continue }
        sortFileTree(&children, using: sortOrder)
        files[index].children = children
    }
}
  1. 修改排序触发逻辑
    将原来的onChange代码替换为调用递归排序函数:
.onChange(of: sortOrder) { _, newValue in
    sortFileTree(&fileTree, using: newValue)
}
说明

这个函数会先对当前层级的数组排序,再递归进入每个子节点的children数组重复排序操作,确保从根到所有子层级的节点都会遵循选中的排序规则重新排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:34:55