【问题标题】:How to incorporate a UISearchController into SwiftUI NavigationView by using UINavigationController's searchController property?如何使用 UINavigationController 的 searchController 属性将 UISearchController 合并到 SwiftUI NavigationView 中?
【发布时间】:2019-12-22 20:25:55
【问题描述】:

我正在尝试创建一个 SwiftUI 视图,其中我有一个包含自定义 MapView(包装 MKMapView)的 NavigationView,但是,我似乎无法将搜索控制器集成到 NavigationView 中,这与您的方式不同使用 UINavigationController 可以轻松实现。我尝试创建自己的自定义 NavigationView 并取得了一些成功,但我并不特别想重新创建该范围的某些内容以添加一项功能(除非这是唯一的解决方案)。

实际上,我主要想知道是否可以按照我的要求进行操作,或者这是否是我必须自己实现的,如果可以,如何实现?

谢谢!

import SwiftUI

struct CustomNavigationController<Content: View>: UIViewControllerRepresentable {
    var title: String

    var content: () -> Content

    init(title: String, @ViewBuilder content: @escaping () -> Content) {
        self.content = content
        self.title = title
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<CustomNavigationController<Content>>) -> UINavigationController {
        let contents = UIHostingController(rootView: self.content())
        let nc = UINavigationController(rootViewController: contents)
        nc.navigationBar.prefersLargeTitles = true

        return nc
    }

    func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<CustomNavigationController<Content>>) {
        uiViewController.navigationBar.topItem?.title = title
        let results = SearchResultsController()
        let sc = UISearchController(searchResultsController: results)
        sc.searchResultsUpdater = results
        sc.hidesNavigationBarDuringPresentation = false
        sc.obscuresBackgroundDuringPresentation = false
        uiViewController.navigationBar.topItem?.searchController = sc
    }
}
import UIKit
import MapKit

class SearchResultsController: UITableViewController {
    let reuseIdentifier = "Cell"

    var results: [MKMapItem] = []

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return results.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)

        let selected = results[indexPath.row].placemark

        print(selected)

        cell.textLabel?.text = selected.title
        cell.detailTextLabel?.text = selected.title

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Clicked")
    }
}

extension SearchResultsController : UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {
        guard let searchBarText = searchController.searchBar.text else { return }

        let request = MKLocalSearch.Request()
        request.naturalLanguageQuery = searchBarText
        request.region = .init()

        let search = MKLocalSearch(request: request)

        search.start(completionHandler: { response, error in
            guard let response = response else { return }

            self.results = response.mapItems
            self.tableView.reloadData()
        })
    }
}

这是我的自定义 UINavigationController 的代码,用于制作类似于 NavigationView 的内容。这可以工作并在导航栏中显示搜索栏,但它并不理想,我也不认为这是最佳做法。

【问题讨论】:

    标签: swift swiftui ios-navigationview


    【解决方案1】:

    我能够在不使用UINavigationControllerUIViewControllerRepresentable 中完成这项工作。事实上,在我自己回答this question 的实验中,我发现当视图更新时,这是一种非常容易出错的方法。

    这里的技术类似于那个问题:使用虚拟UIViewController 来配置您的导航。

    
    struct ContentView: View {
        var body: some View {
            NavigationView {
                NavigationLink(destination: Text("Bye")) {
                    Text("Hi")
                        .background(SearchControllerSetup())
                        .navigationBarTitle("Hello", displayMode: .inline)
                }
            }
        }
    }
    
    struct SearchControllerSetup: UIViewControllerRepresentable {
        typealias UIViewControllerType = UIViewController
    
        func makeCoordinator() -> SearchCoordinator {
            return SearchCoordinator()
        }
    
        func makeUIViewController(context: Context) -> UIViewController {
            return UIViewController()
        }
    
        func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
            // This will be called multiple times, including during the push of a new view controller
            if let vc = uiViewController.parent {
                vc.navigationItem.searchController = context.coordinator.search
            }
        }
    
    }
    
    class SearchCoordinator: NSObject {
    
        let updater = SearchResultsUpdater()
        lazy var search: UISearchController = {
            let search = UISearchController(searchResultsController: nil)
            search.searchResultsUpdater = self.updater
            search.obscuresBackgroundDuringPresentation = false
            search.searchBar.placeholder = "Type something"
            return search
        }()
    }
    
    class SearchResultsUpdater: NSObject, UISearchResultsUpdating {
        func updateSearchResults(for searchController: UISearchController) {
            guard let text = searchController.searchBar.text else { return }
            print(text)
        }
    }
    

    结果:

    【讨论】:

    • 你是否在uiViewController.parent中使用parent来引用NavigationView?另外我假设协调器通常是尝试在 SwiftUI 中实现 UIViewController 功能的最佳方式,这是正确的吗?
    • 我会注意到我尝试使用 if let nc = uiViewController.navigationController 来执行此操作,但我无法让它工作,所以也许父对象会有所帮助!谢谢!
    • .parent 最终引用了包含SearchControllerSetupUIHostingController。主机控制器保存在由NavigationView 创建的UINavigationController 中。在这一点上是的,这种解决方法是你最好的选择。 Apple 几乎肯定会在 iOS 14+ 中提供更好的解决方案。
    【解决方案2】:

    (编辑)iOS 15:

    iOS 15 添加了新属性.searchable()。您可能应该改用它。

    原文:

    如果有人还在寻找,我只是让 a package 真正干净地处理这个问题,灵感来自 @arsenius 的回答

    我还在这里为那些不喜欢链接或只想复制/粘贴的人提供完整的相关源代码。

    扩展名:

    // 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)
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-22
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多