类型“ UIViewController”的值没有成员“ mapView”;您是说'loadView'吗?

时间:2019-02-09 21:22:55

标签: mkmapview mklocalsearch

我尝试在Swift4(适用于iOS 12)中使用MKLocalSearchRequest搜索位置。当我在viewDidLoad的末尾附加locationSearchTable.mapView = mapView时出现错误。

在ViewController中

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {


    @IBOutlet weak var mapView: MKMapView!

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

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()

        let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable")
        resultSearchController = UISearchController(searchResultsController: locationSearchTable)
        resultSearchController?.searchResultsUpdater = locationSearchTable as! UISearchResultsUpdating

        let searchBar = resultSearchController!.searchBar
        searchBar.sizeToFit()
        searchBar.placeholder = "Search for places"
        navigationItem.titleView = resultSearchController?.searchBar

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

        locationSearchTable.mapView = mapView

    }...


在LocationSearchTable

import UIKit
import MapKit


class LocationSearchTable: UITableViewController {

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

}

extension LocationSearchTable: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {
        guard let mapView = mapView,
            let searchBarText = searchController.searchBar.text else { return }
        let request = MKLocalSearch.Request()
        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.tableView.reloadData()
        }
    }
}...

1 个答案:

答案 0 :(得分:0)

也许locationSearchTable不是LocationSearchTable类。

尝试以下代码

if let locationSearchTable = locationSearchTable as? LocationSearchTable {
    locationSearchTable.mapView = mapView
}