问题描述
我正在使用 SwiftUI 创建一个项目,并希望向导航栏中添加一个搜索栏,就像本机设置应用程序、邮件应用程序等中存在的内容一样.
I'm creating a project using SwiftUI and would like to add a search bar to the navigation bar like what exists in the native settings app, mail app, etc.
我已经尝试了一些东西,但无法让它发挥作用.下面的代码运行良好,但即使我包含 navigationController.navigationItem.hidesSearchBarWhenScrolling = false
,搜索栏也不会显示(我试过向上滚动).任何帮助将不胜感激.
I've tried a few things, but can't quite get it to work. The following code runs fine, but the search bar won't show up (I've tried scrolling up) even if I include navigationController.navigationItem.hidesSearchBarWhenScrolling = false
. Any help would be appreciated.
//
// ContentView.swift
// SwiftUITest
//
// Created by me on 1/7/20.
// Copyright © 2020 me. All rights reserved.
//
import SwiftUI
struct HomeView: View {
var body: some View {
ScrollView {
HStack {
Spacer(minLength: 0)
Text("Hello World")
Spacer(minLength: 0)
}
}
.navigationBarTitle(Text("Search"))
}
}
struct SecondView: View {
var body: some View {
return Text("Second View")
}
}
struct CustomUIViewControllerRepresentation: UIViewControllerRepresentable {
typealias UIViewControllerType = UINavigationController
func makeUIViewController(context: Context) -> UINavigationController {
let viewController = UIHostingController(rootView: HomeView())
let navigationController = UINavigationController(rootViewController: viewController)
navigationController.navigationBar.prefersLargeTitles = true
let searchController = UISearchController()
navigationController.navigationItem.searchController = searchController
return navigationController
}
func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
}
}
struct ContentView: View {
var body: some View {
CustomUIViewControllerRepresentation()
}
}
推荐答案
(编辑)iOS 15:
iOS 15 添加了新属性 .searchable()
.你可能应该改用它.
(EDIT) iOS 15:
iOS 15 added the new property .searchable()
. You should probably use that instead.
如果有人还在看,我做了一个包来解决这个问题,因为所有其他我发现的解决方案存在一些问题.
If anyone is still looking, I made a package to deal with this, since all the other solutions I found had some problem or other.
我还在此处为那些不喜欢链接或只想复制/粘贴的人提供了完整的相关源代码.
I'm also including the full relevant source code here for those who dislike links or just want to copy/paste.
扩展:
// Copyright © 2020 thislooksfun
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import SwiftUI
import Combine
public extension View {
public func navigationBarSearch(_ searchText: Binding<String>) -> some View {
return overlay(SearchBar(text: searchText).frame(width: 0, height: 0))
}
}
fileprivate struct SearchBar: UIViewControllerRepresentable {
@Binding
var text: String
init(text: Binding<String>) {
self._text = text
}
func makeUIViewController(context: Context) -> SearchBarWrapperController {
return SearchBarWrapperController()
}
func updateUIViewController(_ controller: SearchBarWrapperController, context: Context) {
controller.searchController = context.coordinator.searchController
}
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text)
}
class Coordinator: NSObject, UISearchResultsUpdating {
@Binding
var text: String
let searchController: UISearchController
private var subscription: AnyCancellable?
init(text: Binding<String>) {
self._text = text
self.searchController = UISearchController(searchResultsController: nil)
super.init()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = true
searchController.obscuresBackgroundDuringPresentation = false
self.searchController.searchBar.text = self.text
self.subscription = self.text.publisher.sink { _ in
self.searchController.searchBar.text = self.text
}
}
deinit {
self.subscription?.cancel()
}
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
self.text = text
}
}
class SearchBarWrapperController: UIViewController {
var searchController: UISearchController? {
didSet {
self.parent?.navigationItem.searchController = searchController
}
}
override func viewWillAppear(_ animated: Bool) {
self.parent?.navigationItem.searchController = searchController
}
override func viewDidAppear(_ animated: Bool) {
self.parent?.navigationItem.searchController = searchController
}
}
}
用法:
import SwiftlySearch
struct MRE: View {
let items: [String]
@State
var searchText = ""
var body: some View {
NavigationView {
List(items.filter { $0.localizedStandardContains(searchText) }) { item in
Text(item)
}.navigationBarSearch(self.$searchText)
}
}
}
这篇关于在 SwiftUI 中向 NavigationView 添加搜索栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!