You need to enable JavaScript to run this app. SwiftUI如何通过DisclosureGroup选中项实现关联列表筛选
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI如何通过DisclosureGroup选中项实现关联列表筛选

选项联动过滤产品列表的实现方法

整个改动不需要重构原有UI和数据结构,仅需两个小调整就能实现预期的联动效果:

  • 新增一个绑定选中状态的计算属性,根据当前选中的选项值对原始产品数组做实时筛选
  • 把List组件里原本渲染的全量产品数组,替换成筛选后的结果

因为selectedOption是@State修饰的视图状态,值变化时会自动触发视图重渲染,筛选逻辑不需要额外写手动刷新的代码。

struct ProductList: View {
    @State private var selectedOption = "Option 1"
    @State private var isExpanded = false

    let options = ["Option 1", "Option 2", "Option 3", "Option 4"]
    let products: [ProductModel] = productData

    // 实时根据选中值过滤匹配的产品
    var filteredProducts: [ProductModel] {
        products.filter { $0.option == selectedOption }
    }

    var body: some View {
        VStack {
            DisclosureGroup("\(selectedOption)", isExpanded: $isExpanded) {
                ScrollView{
                    VStack{
                        ForEach(options, id: \.self) { item in
                            Text(item)
                                .onTapGesture {
                                    selectedOption = item
                                    withAnimation {
                                        isExpanded.toggle()
                                    }
                                }
                        }
                    }
                }
            }
            // 替换为过滤后的产品列表渲染
            List{
                ForEach(filteredProducts) { item in
                    NavigationLink(destination: ProductTabView(product: item)) {
                        ProductListRow(product: item)
                    }
                }
            }
        }
    }
}

// 原有数据模型与示例数据无需调整
struct ProductModel: Identifiable {
     var id = UUID()
     var title: String
     var option: String  
}

let productData: [ProductModel] = [
    ProductModel(
        title: "product1",
        option: "Option 1"
    ),
    ProductModel(
        title: "product2",
        option: "Option 2"
    ),
    ProductModel(
        title: "product3",
        option: "Option 1"
    ),
]

补充说明:如果后续需要增加“显示全部产品”的筛选选项,只需要在options数组中新增对应选项,再在filteredProducts的过滤逻辑里加分支判断:当选中值为“全部”时直接返回原始全量products数组即可,整个联动逻辑不需要额外改动其他部分。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.24 08:06:02