我试图在我的应用程序中隐藏搜索栏,就像 Apple 在他们的消息应用程序中所做的那样:
我已经在 SwiftUI 中实现了 UISearchBar:
struct SearchBar: UIViewRepresentable {
@Binding var text: String
class Coordinator: NSObject, UISearchBarDelegate {
@Binding var text: String
init(text: Binding<String>) {
_text = text
}
func searchBar(_: UISearchBar, textDidChange searchText: String) {
text = searchText
}
}
func makeCoordinator() -> SearchBar.Coordinator {
return Coordinator(text: $text)
}
func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
searchBar.searchBarStyle = .minimal
searchBar.placeholder = "????? ?? ????????, ???????? ??? ????????"
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context _: UIViewRepresentableContext<SearchBar>) {
uiView.text = text
}
}
Run Code Online (Sandbox Code Playgroud)
如何在 SwiftUI 中实现隐藏和隐藏动画?
苹果以非常本土化的方式让这一切成为可能。
您只需要对.searchable()要使其可搜索的视图使用修饰符,并确保您将其NavigationView作为视图的父级。
例子
struct CountriesView: View {
let countries = ["United States", "India", "Ukraine", "Russia", "Sweden"]
@State var search: String = ""
var body: some View {
NavigationView {
List(countries.filter({
// we filter our country list by checking whether country name
// does contain search string or not
$0.lowercased().contains(search.lowercased())
})) { country in
Text(country)
}.searchable(text: $search)
}
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您可以使用计算属性以更方便的方式过滤数组。
然后,示例中过滤器的计算属性将是:
var searchResults: [String] {
return countries.filter({$0.lowercased().contains(search.lowercased())})
}
Run Code Online (Sandbox Code Playgroud)
所以,List看起来像这样:
List(searchResults) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
ps,您可以在这篇 swift.org 文章中了解有关计算变量和属性的更多信息
| 归档时间: |
|
| 查看次数: |
709 次 |
| 最近记录: |