一、首先看一下iOS15之前的搜索框
搜索框需要自己写 功能等方面也需要自己实现
struct NewSearch: View {
let names = ["Raju", "Ghanshyam", "Baburao Ganpatrao Apte", "Anuradha", "Kabira", "Chaman Jhinga", "Devi Prasad", "Khadak Singh"]
@State private var searchTerm : String = ""
var body: some View {
NavigationView{
List {
SearchBar(text: $searchTerm)
ForEach(self.names.filter{
self.searchTerm.isEmpty ? true : $0.localizedStandardContains(self.searchTerm)
}, id: \.self) { name in
Text(name)
}
}
.navigationBarTitle(Text("Search Bar"))
}
}
}
struct SearchBar : UIViewRepresentable {
@Binding var text : String
class Cordinator : NSObject, UISearchBarDelegate {
@Binding var text : String
init(text : Binding<String>) {
_text = text
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
}
}
func makeCoordinator() -> SearchBar.Cordinator {
return Cordinator(text: $text)
}
func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) {
uiView.text = text
}
}
image.png
二、iOS15新增
struct ContentView: View {
let names = ["Holly", "Josh", "Rhonda", "Ted"]
@State private var searchText = ""
var body: some View {
NavigationView {
List {
ForEach(searchResults, id: \.self) { name in
NavigationLink(destination: Text(name)) {
Text(name)
}
}
}
.searchable(text: $searchText) {
ForEach(searchResults, id: \.self) { result in
Text("Are you looking for \(result)?").searchCompletion(result)
}
}
.navigationTitle("Contacts")
}
}
var searchResults: [String] {
if searchText.isEmpty {
return names
} else {
return names.filter { $0.contains(searchText) }
}
}
}
searchable
只能在导航控制器中使用,通过绑定的字符串可直接实现搜索
在未实现搜索建议的时候,进行的是模糊搜索
.searchable(text: $searchText, prompt: "搜索", suggestions: {
ForEach(searchResults, id: \.self) { result in
Text("Are you looking for \(result)?").searchCompletion(result)
}
})
实现搜索建议 点击可以搜索某一项
image.png
三、注意事项
iOS15新增的searchable 只能在 NavigationView 中使用
网友评论