Uitableview 从故事板创建的搜索栏不';t连接UISearchController

Uitableview 从故事板创建的搜索栏不';t连接UISearchController,uitableview,mapkit,uisearchbar,uistoryboard,uisearchcontroller,Uitableview,Mapkit,Uisearchbar,Uistoryboard,Uisearchcontroller,我以编程方式创建了一个连接到UITableViewController的搜索栏 let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable resultSearchController = UISearchController(searchResultsController: l

我以编程方式创建了一个连接到UITableViewController的搜索栏

  let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: 
   "LocationSearchTable") as! LocationSearchTable
   resultSearchController = UISearchController(searchResultsController: 
   locationSearchTable)
    resultSearchController.searchResultsUpdater = locationSearchTable
    let searchBar = resultSearchController.searchBar
    searchBar.sizeToFit()
    searchBar.placeholder = "Search for places"
    navigationItem.titleView = resultSearchController.searchBar
    resultSearchController.searchBar.delegate = self
    resultSearchController.hidesNavigationBarDuringPresentation = false
    resultSearchController.obscuresBackgroundDuringPresentation = true
    definesPresentationContext = true
    locationSearchTable.mapView = mapView
    locationSearchTable.handleMapSearchDelegate = self

它工作得很好。但是,当我尝试将搜索栏分配给从故事板创建的搜索栏时,它们不起作用。我也委派了故事板上的连接

class MapViewController: UIViewController, UISearchBarDelegate, 
 UITableViewDelegate {

   @IBOutlet weak var myFrom: UISearchBar!
   @IBOutlet weak var myTo: UISearchBar!
    ....
    override func viewDidLoad() { 
    ...
    myFrom = resultSearchController.searchBar
    myTo = resultSearchController.searchBar
    myFrom.delegate = self
    myTo.delegate = self
我还需要tableview结果与弹出视图中的搜索栏具有相同的宽度。不是以编程方式创建的整个屏幕宽度

我使用搜索栏中的子定位数据。现在,我只是将数据从MKPlacemarks拉到搜索栏中

我无法激活搜索栏

TableView代码:

    import Foundation
    import UIKit
    import MapKit

    class LocationSearchTable : UITableViewController {
    var handleMapSearchDelegate: HandleMapSearch? = nil
    var mapView: MKMapView? = nil
    var searchResults = [MKLocalSearchCompletion]()
    private var boundingRegion: MKCoordinateRegion = MKCoordinateRegion(MKMapRect.world)

    lazy var searchCompleter: MKLocalSearchCompleter = {
          let sC = MKLocalSearchCompleter()
          sC.delegate = self
          sC.resultTypes = .pointOfInterest
          sC.region = boundingRegion
          return sC
      }()

    private var places: [MKMapItem]? {
          didSet {
              tableView.reloadData()
           }
      }

    private var localSearch: MKLocalSearch? {
          willSet {
              // Clear the results and cancel the currently running local search before starting a new search.
              places = nil
              localSearch?.cancel()
          }
      }

    /// - Parameter suggestedCompletion: A search completion provided by `MKLocalSearchCompleter` when tapping on a search completion table row
      private func search(for suggestedCompletion: MKLocalSearchCompletion) {
          let searchRequest = MKLocalSearch.Request(completion: suggestedCompletion)
            search(using: searchRequest)
      }

    /// - Tag: SearchRequest
    private func search(using searchRequest: MKLocalSearch.Request) {
        // Confine the map search area to an area around the user's current location.
        searchRequest.region = boundingRegion

        localSearch = MKLocalSearch(request: searchRequest)
        localSearch?.start { [unowned self] (response, error) in
            guard error == nil else {
                self.displaySearchError(error)
                return
            }

            self.places = response?.mapItems

            // Used when setting the map's region in `prepareForSegue`.
            if let updatedRegion = response?.boundingRegion {
                self.boundingRegion = updatedRegion
            }
        }
    }

        private func displaySearchError(_ error: Error?) {
            if let error = error as NSError?, let errorString = error.userInfo[NSLocalizedDescriptionKey] as? String {
                let alertController = UIAlertController(title: "Could not find any places.", message: errorString, preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                present(alertController, animated: true, completion: nil)
            }
        }

    }


      extension LocationSearchTable: UISearchResultsUpdating {

         func updateSearchResults(for searchController: UISearchController) 

{

      searchCompleter.queryFragment =  searchController.searchBar.text ?? ""

          self.tableView.reloadData()

      }
  }


extension LocationSearchTable: MKLocalSearchCompleterDelegate {

    func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
        searchResults = completer.results
         self.tableView.reloadData()
    }

    func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
        // handle error
        print("error loading MKLocalSearchCompleter")
    }
}


//-   Tableview DataSource methods

extension LocationSearchTable {

    override func numberOfSections(in tableView: UITableView) -> Int {
           return 1
       }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
           let searchResult = searchResults[indexPath.row]
           let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
           cell.textLabel?.text = searchResult.title
           cell.detailTextLabel?.text = searchResult.subtitle

        return cell
       }

    override func tableView(_ tableView: UITableView, didSelectRowAt  indexPath: IndexPath) {

        let selectedItem = searchResults[indexPath.row]
        let request = MKLocalSearch.Request()
        request.naturalLanguageQuery = selectedItem.title

        let search = MKLocalSearch(request: request)
        search.start { (response, error) in
        guard let response = response else {return}
        guard let item = response.mapItems.first else {return}

        self.handleMapSearchDelegate?.dropPinZoomIn(placemark: item.placemark)
        self.dismiss(animated: true, completion: nil)

    }
  }
}


“但当我尝试将搜索栏分配给从情节提要创建的搜索栏时,它们不起作用。”您可能应该在尝试分配的位置显示代码?如果您需要tableview具有与搜索栏相同的宽度-我猜tableview也是由搜索栏组件创建的?您是否有任何显示tableview创建的代码要输入?谢谢您的评论。我按照你的建议编辑了这个问题。我可能在委派方面有问题,但无法修复。LocationSearchTable是我在另一个文件中创建的UITableViewController。