SwiftUI 过滤列表
Posted
技术标签:
【中文标题】SwiftUI 过滤列表【英文标题】:SwiftUI Filtering a List 【发布时间】:2021-01-13 17:50:24 【问题描述】:基本上我有一个名为Treatment
的可解码结构,它有两个参数:标题和类别。我想创建一个列表,其中categoryName = treatment.category
。这样,只有部分治疗会成为列表的一部分。
struct HomeSecondLevel: View
let categoryName: String
@ObservedObject var treatmentsManager = TreatmentsManager()
var body: some View
NavigationView
List(treatmentsManager.treatments) treatment in
Text(treatment.title)
我尝试在列表视图正下方添加一个“if 语句”(if categoryName = treatment.category
),作为过滤列表的尝试,但它不起作用。
【问题讨论】:
【参考方案1】:我通过将 过滤 数据传递给 List
来解决此问题,并在 filteredTreatments
中计算。
在您的问题中,if categoryName = treatment.category
不起作用,因为您写的是 =
而不是 ==
。如果修复它会起作用,但它会显示Treatment
与类别不匹配的空白/行。为了避免出现空格,所以这里的数据先被过滤掉。
这是一个适合你的例子:
struct ContentView: View
var body: some View
HomeSecondLevel(categoryName: "e")
struct HomeSecondLevel: View
@ObservedObject var treatmentsManager = TreatmentsManager()
let categoryName: String
var filteredTreatments: [Treatment]
treatmentsManager.treatments.filter $0.category == categoryName
var body: some View
NavigationView
List(filteredTreatments) treatment in
Text(treatment.title)
class TreatmentsManager: ObservableObject
@Published var treatments: [Treatment] = [
Treatment(title: "1", category: "o"),
Treatment(title: "2", category: "e"),
Treatment(title: "3", category: "o"),
Treatment(title: "4", category: "e"),
Treatment(title: "5", category: "o"),
Treatment(title: "6", category: "e"),
]
struct Treatment: Identifiable
let id = UUID()
let title: String
let category: String
【讨论】:
以上是关于SwiftUI 过滤列表的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI + Firestore - 基于从 Firestore 返回的数组的过滤器列表