SwiftUI项目实现搜索功能

实现

创建变量

1
@State var search: String = ""

过滤

此处过滤条件为判断元素是否包含搜索的文本。

1
<Your-Array>.filter({"\($0)".contains(search.lowercased()) || search.isEmpty})

汇总

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
struct DataList: View {

  @State var search: String = ""
  @Binding var dataList: [Item]

  var dataSearchFilterList: [Item] {
    dataList.filter({"\($0)".contains(search.lowercased()) || search.isEmpty})
  }

  var body: some View {
    if dataSearchFilterList.isEmpty {
      Text("搜索不到...")
    } else {
      ... // 展示搜索结果
    }
  }
  
}
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy