我正在尝试实现搜索控制器。从阵列中显示的一切都很好。现在我试图显示MapKit的结果,我在collectionView中看不到任何内容。我正在以编程方式执行所有操作,因此可能是我将collectionView作为resultsView调用。我做错了什么?
这是主要的ViewController: 导入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 :(得分:0)
似乎我在使用:
func updateSearchResultsForSearchController
当我打算使用时:
func updateSearchResults(for searchController: UISearchController) {
将updateSearchResultsForSearchController中的代码复制到updateSearchResults可以解决这个问题,因为这是我使用错误的正常实现。