在SwiftUI中使用搜索栏过滤对象数组可以通过以下步骤实现:
Person
的结构体,具有name
和age
属性。struct Person {
let name: String
let age: Int
}
@State
属性来存储搜索关键字和过滤后的结果。@State private var searchText = ""
@State private var filteredPersons: [Person] = []
body
中,添加一个TextField
作为搜索栏,并将搜索关键字绑定到searchText
属性。TextField("Search", text: $searchText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
filter
方法对对象数组进行过滤,将过滤后的结果存储在filteredPersons
属性中。filteredPersons = persons.filter { person in
return person.name.localizedCaseInsensitiveContains(searchText)
}
上述代码中,persons
是包含所有对象的数组。
ForEach
循环遍历过滤后的结果,并显示每个对象的属性。List(filteredPersons, id: \.self) { person in
Text(person.name)
Text("\(person.age)")
}
完整的示例代码如下:
import SwiftUI
struct ContentView: View {
struct Person {
let name: String
let age: Int
}
let persons = [
Person(name: "John", age: 25),
Person(name: "Jane", age: 30),
Person(name: "Alice", age: 35)
]
@State private var searchText = ""
@State private var filteredPersons: [Person] = []
var body: some View {
VStack {
TextField("Search", text: $searchText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
List(filteredPersons, id: \.self) { person in
Text(person.name)
Text("\(person.age)")
}
}
.onAppear {
filteredPersons = persons
}
.onChange(of: searchText) { newValue in
filteredPersons = persons.filter { person in
return person.name.localizedCaseInsensitiveContains(searchText)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
这样,当用户在搜索栏中输入关键字时,列表将根据关键字过滤并显示匹配的对象。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云