我正在尝试创建一个 SwiftUI View ,其中我有一个包装自定义 MapView(包装 MKMapView)的 NavigationView,但是,成功率极低,我似乎无法将搜索 Controller 集成到 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 的东西。这有效并在导航栏中显示搜索栏,但它并不理想,我也不觉得这是最佳实践。

最佳答案

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

此处的技术类似于该问题:使用虚拟 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)
    }
}

结果:
swift - 如何使用 UINavigationController 的 searchController 属性将 UISearchController 合并到 SwiftUI NavigationView 中?-LMLPHP

关于swift - 如何使用 UINavigationController 的 searchController 属性将 UISearchController 合并到 SwiftUI NavigationView 中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59447798/

10-14 20:00