我正在尝试学习Swift,SwiftUI和Combine,并且对iOS来说是新手。最终,我希望有一个可以搜索,过滤和排序的列表。
到目前为止,当我在TextField中使用onEditingChanged
时,我的过滤工作正常,但这需要按回车键。我只是想不通如何在TextField activePeople
更改时如何触发filterText
进行更新,以便activePeople
列表在您键入时 进行过滤。
当我在视图中过滤ForEach中的列表时,我已经有了一个可用的版本(请参阅注释掉的代码),但最终过滤和排序将变得更加复杂,将其置于外部似乎更有意义该视图。让我知道由于某种原因这不是正确的方法。
这是到目前为止的代码:
import Combine
import SwiftUI
class Model: ObservableObject {
@Published var filterText: String = “”
@Published var activePeople: [Person] = []
private var allPeople : [Person] = [
Person( id: 1000, name: “Alexa” ),
Person( id: 1001, name: “Anaïs” ),
Person( id: 1002, name: “Earl” ),
Person( id: 1003, name: “Elba” ),
Person( id: 1004, name: "Emil” ),
Person( id: 1005, name: “Janeth” ),
Person( id: 1006, name: “Joselyn” ),
Person( id: 1007, name: “Lupita” ),
Person( id: 1008, name: “Mellie” ),
Person( id: 1009, name: “Vanita” ),
]
init() {
activePeople = allPeople
}
func filterList() {
if ( filterText == “” ) {
activePeople = allPeople
} else {
activePeople = allPeople.filter( { $0.name.localizedStandardContains( filterText ) } )
}
}
}
struct Person: Identifiable {
var id: Int
var name: String
}
import SwiftUI
struct ContentView: View {
@EnvironmentObject private var model: Model
var body: some View {
VStack {
Form {
Section {
TextField(“Filter Text”, text: $model.filterText, onEditingChanged: {_ in self.model.filterList()}
)
}
Section {
Text( "Filtered by: \(model.filterText)” )
ForEach( model.activePeople ) { person in
// if ( self.model.filterText == “” || person.name.localizedStandardContains( self.model.filterText )) {
Text( person.name )
// }
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(Model())
}
}
答案 0 :(得分:0)
只需在您的ContentView中应用过滤:
ForEach(model.activePeople.filter({ self.model.filterText.isEmpty ||
$0.name.localizedStandardContains(self.model.filterText)})) { person in
Text( person.name )
}
答案 1 :(得分:0)
为了观察文本字段输入的变化,可以观察模型中的变量。从视图中删除过滤逻辑可能也是一个好主意。
一个示例是在模型初始化时开始观察filterText
。另外,请记住保留对从sink
返回的可取消对象的引用。
我们所做的是每次filterText
中的值发生变化(并且由于文本字段绑定而发生变化)时,我们将过滤数组并将值分配给activePeople
变量
var filterCancellable: AnyCancellable?
init() {
filterCancellable = $filterText.sink {[weak self] currentText in
guard let strongSelf = self else { return }
strongSelf.activePeople = strongSelf.filterList(with: currentText)
}
}
func filterList(with text: String) -> [Person] {
if ( text == "" ) {
return allPeople
} else {
return allPeople.filter( { $0.name.localizedStandardContains( text ) } )
}
}
这样您以后就可以做
var body: some View {
VStack {
Form {
Section {
TextField("Filter Text", text: $model.filterText)
}
Section {
Text( "Filtered by: \(model.filterText)" )
ForEach( model.activePeople ) { person in
Text( person.name )
}
}
}
}
}