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

SwiftUI中含children的List如何修改行背景色高亮选中项?

在SwiftUI树形List中高亮选中行的方案

当使用List的children参数实现层级目录结构时,依然可以通过自定义行视图+绑定选中状态的方式实现行背景高亮,具体步骤如下:

  1. 定义带层级的数据源模型
    确保你的数据模型遵循Identifiable协议,包含children属性:
struct DirectoryItem: Identifiable {
    let id = UUID()
    var name: String
    var children: [DirectoryItem]?
}
  1. 绑定选中状态并自定义行视图
    在List中绑定选中的项目ID(单选用单个ID,多选用Set<ID>),然后在自定义的行视图中通过判断当前项目是否被选中,设置listRowBackground:

单选场景示例

struct DirectoryListView: View {
    @State private var directoryItems: [DirectoryItem] = [
        DirectoryItem(name: "主目录1", children: [
            DirectoryItem(name: "子目录1-1"),
            DirectoryItem(name: "子目录1-2", children: [
                DirectoryItem(name: "子目录1-2-1")
            ])
        ]),
        DirectoryItem(name: "主目录2")
    ]
    @State private var selectedItemID: DirectoryItem.ID?
    
    var body: some View {
        List(directoryItems, id: \.id, children: \.children, selection: $selectedItemID) { item in
            Text(item.name)
                .listRowBackground(selectedItemID == item.id ? Color.blue.opacity(0.3) : Color.clear)
        }
    }
}

多选场景示例

如果需要支持多选,将选中状态改为Set<DirectoryItem.ID>,并开启编辑模式:

struct DirectoryListView: View {
    @State private var directoryItems: [DirectoryItem] = [/* 数据源 */]
    @State private var selectedItemIDs: Set<DirectoryItem.ID> = []
    
    var body: some View {
        List(directoryItems, id: \.id, children: \.children, selection: $selectedItemIDs) { item in
            Text(item.name)
                .listRowBackground(selectedItemIDs.contains(item.id) ? Color.blue.opacity(0.3) : Color.clear)
        }
        .environment(\.editMode, .constant(.active))
    }
}
  1. 注意事项
  • 必须给List指定id参数(比如id: \.id),确保每个项目的唯一性,否则选中状态判断会失效。
  • 若需要更复杂的行样式,可以将行内容封装为独立的View,在其中处理背景逻辑,保持代码整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:55:25