0

我想實現一個搜索控制器。從數組中顯示一切正常。現在我試圖顯示來自MapKit的結果,並且在collectionView中看不到任何東西。我正在做所有事情,所以它可能是我如何調用collectionView作爲resultsView。我究竟做錯了什麼?SearchController不顯示程序集合查看單元格

這是主視圖控制器: 進口的UIKit 進口MapKit

class LocationVC: UIViewController, MKMapViewDelegate { 

    let locationManager = CLLocationManager() 
    var resultSearchController:UISearchController? = nil 

    let mapView : MKMapView = { 
     let map = MKMapView() 
     map.translatesAutoresizingMaskIntoConstraints = false 
     return map 
    }() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let window = UIWindow.init(frame: UIScreen.main.bounds) 
     window.makeKeyAndVisible() 

     setupBasicNavigation(title: "") 
     setupLocationManager() 
     setupMapView() 

     mapView.delegate = self 
     mapView.showsUserLocation = true 

     navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelAndGoBack)) 

     setupSearchController() 
     searchBarSetup() 


    } 

    //MARK: Setting up the Search Bar 
    func searchBarSetup() { 
     let searchBar = resultSearchController!.searchBar 
     searchBar.sizeToFit() 
     searchBar.placeholder = "Search for places" 
     navigationItem.titleView = resultSearchController?.searchBar 

     resultSearchController?.hidesNavigationBarDuringPresentation = false 
     resultSearchController?.dimsBackgroundDuringPresentation = true 
     definesPresentationContext = true 
    } 

    //MARK: Setting up the Search Controller 
    func setupSearchController() { 
     let locationSearchTable = LocationSearchTable() 
     resultSearchController = UISearchController(searchResultsController: locationSearchTable) 
     resultSearchController?.searchResultsUpdater = locationSearchTable as UISearchResultsUpdating 
     locationSearchTable.modalPresentationStyle = .currentContext 
     self.present(locationSearchTable, animated: false, completion: nil) 
     locationSearchTable.mapView = mapView 
     //self.present(locationSearchTable, animated: false, completion: nil) 
    } 

    //MARK: Setting up the Map View 
    func setupMapView() { 
     view.addSubview(mapView) 
     mapView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true 
     mapView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true 
     mapView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true 
     mapView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true 
    } 

    //MARK: Setting up the Location Manager 
    func setupLocationManager() { 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestWhenInUseAuthorization() 
     locationManager.requestLocation() 
    } 

    //MARK: Sends to the back controller 
    func cancelAndGoBack() { 
     print("Canceled and Saved") 
     self.dismiss(animated: true, completion: nil) 
    } 


} 

//MARK: Extension to provide the delegates methods for LOcation 
extension LocationVC : CLLocationManagerDelegate { 
    private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
     if status == .authorizedWhenInUse { 
      locationManager.requestLocation() 
     } 
    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     if let location = locations.first { 
      let span = MKCoordinateSpanMake(0.05, 0.05) 
      let region = MKCoordinateRegion(center: location.coordinate, span: span) 
      mapView.setRegion(region, animated: true) 
     } 
    } 

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 
     print("error:: \(error)") 
    } 
} 

這是結果的視圖控制器:

import UIKit 
import MapKit 

class LocationSearchTable: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { 

    var collectionView: UICollectionView! 

    var matchingItems:[MKMapItem] = [] 
    var mapView: MKMapView? = nil 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let window = UIWindow.init(frame: UIScreen.main.bounds) 
     window.makeKeyAndVisible() 

     setupCollectionView() 
     setupBasicNavigation(title: "") 


    } 

    //MARK: Setup CollectionView 
    func setupCollectionView() { 

     let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() 
     layout.sectionInset = UIEdgeInsets(top: 50, left: 0, bottom: 110, right: 0) 
     layout.itemSize = CGSize(width: view.frame.size.width, height: 40) 

     layout.minimumLineSpacing = 1 

     collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) 
     collectionView.dataSource = self as UICollectionViewDataSource 
     collectionView.delegate = self 

     //collection view design 
     collectionView?.backgroundColor = UIColor(r: 242, g: 240, b: 240) 
     collectionView?.alwaysBounceVertical = false 
     collectionView?.showsVerticalScrollIndicator = false 
     collectionView?.scrollsToTop = false 

     collectionView.register(LocationCell.self, forCellWithReuseIdentifier: "LocationCell") 

    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return matchingItems.count 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LocationCell", for: indexPath) as! LocationCell 
     cell.contentView.backgroundColor = .white 
     cell.layer.borderColor = UIColor(white: 0.5, alpha: 0.3).cgColor 
     cell.layer.borderWidth = 0.3 

     let selectedItem = matchingItems[indexPath.row].placemark 
     cell.itemName.text = selectedItem.name 

     return cell 
    } 

    //cell function to determine size 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 

     return CGSize(width: view.frame.width, height: 40) 
    } 

} 

//MARK: Extension for Search Controller Delegate 
extension LocationSearchTable : UISearchResultsUpdating { 
    func updateSearchResults(for searchController: UISearchController) { 

    } 
    func updateSearchResultsForSearchController(searchController: UISearchController) { 
     guard let mapView = mapView, 
      let searchBarText = searchController.searchBar.text else { return } 
     let request = MKLocalSearchRequest() 
     request.naturalLanguageQuery = searchBarText 
     request.region = mapView.region 
     let search = MKLocalSearch(request: request) 
     search.start { response, _ in 
      guard let response = response else { 
       return 
      } 
      self.matchingItems = response.mapItems 
      self.collectionView.reloadData() 
     } 
    } 
} 

回答

0

看來,我是用:

func updateSearchResultsForSearchController 

當我應該使用:

func updateSearchResults(for searchController: UISearchController) { 

將代碼從updateSearchResultsForSearchController複製到updateSearchResults做了一個竅門,因爲它是我使用錯誤的正常實現。