SwiftUI中如何筛选嵌套对象数组?解决单元导航后仅展示对应成果的问题
兄弟,你的问题核心出在NavigationLink的结构逻辑上——你现在把所有UnitView都塞进同一个导航链接的触发区域,而且目的地直接遍历所有单元的Outcome,这就导致不管点哪个Unit,都会跳转到展示所有成果的页面,完全没关联到你点击的那个单元!
问题根源拆解
- 原
ContentView里,NavigationLink包裹了整个ForEach(model.subject.unit),所有UnitView共享同一个导航链接,点击任何一个都会触发同一个跳转 - 目的地的
ForEach直接遍历所有单元的Outcome,自然会展示全部内容,和点击动作完全脱节
解决方案:给每个Unit绑定独立的导航链接
我们需要让每个Unit对应一个专属的NavigationLink,点击时把当前的unit对象直接传递到目标页面,只展示该单元下的成果。修改后的代码如下:
struct ContentView: View { @EnvironmentObject private var model: SubjectViewModel var body: some View { NavigationView { ScrollView(.vertical) { LazyVGrid(columns: [GridItem(.adaptive(minimum: 300))], spacing: 20) { // 为每个Unit单独创建NavigationLink ForEach(model.subject.unit) { unit in NavigationLink { // 跳转至当前单元的专属详情页 UnitDetailView(unit: unit) } label: { UnitView(unit: unit) .foregroundColor(.primary) } } } } .navigationTitle("Welcome to " + model.subject.name) } .navigationViewStyle(.stack) } } // 新增单元详情视图,专门展示对应单元的成果 struct UnitDetailView: View { let unit: Subject.Unit var body: some View { ScrollView { VStack(spacing: 20) { // 先展示单元基础信息 VStack(alignment: .leading) { Text("Unit \(unit.unitNumber): \(unit.name)") .font(.largeTitle.bold()) Text("Theme: \(unit.theme)") .font(.title) Text(unit.timeFrame.formatted(date: .abbreviated, time: .omitted)) .font(.caption) } .padding() // 只遍历当前单元的Outcome ForEach(unit.outcome) { outcome in OutcomeView(outcome: outcome) .padding() .background(Color.gray.opacity(0.1)) .cornerRadius(10) } } .padding() } .navigationTitle("Unit \(unit.unitNumber) Outcomes") } }
额外说明
你之前尝试用unitNumber匹配单元和成果其实没必要——因为我们已经直接持有了点击的unit对象,直接访问它的outcome属性就可以精准获取对应成果,既简单又避免了编号匹配可能出现的错误。
内容的提问来源于stack exchange,提问作者Alepth
相关产品推荐
相关产品推荐

