xcode MapKit本地搜索结果填充表

hrysbysz  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(106)

我试图加载更新的搜索结果,但它不填充表视图。
我使用了这个链接https://www.thorntech.com/how-to-search-for-location-using-apples-mapkit/,它属于以前的版本,但它仍然工作得很好,除了显示本地搜索结果。

class LocationSearchTable : UITableViewController, UISearchResultsUpdating {
    var matchingItems:[MKMapItem] = []
    var mapView: MKMapView? = nil
    
}

extension LocationSearchTable {
    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 {
                print("No response")
                return
            }
            self.matchingItems = response.mapItems
            self.tableView.reloadData()
        }
    }
}

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        let selectedItem = matchingItems[indexPath.row].placemark
        cell.textLabel?.text = selectedItem.name
        cell.detailTextLabel?.text = ""
        return cell
    }
}
kwvwclae

kwvwclae1#

//use IndexPath rather than NSIndexPath and you need to use 
 //override

override func tableView(_ tableView: UITableView, 
     cellForRowAtIndexPath 
     indexPath: IndexPath) -> UITableViewCell {
  let cell =tableView.dequeueReusableCell(withIdentifier:"cell")!
    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    cell.detailTextLabel?.text = ""
    return cell
}

希望现在回答你还不算太晚!

相关问题