我将下面的UITableViewController附加为searchResultsController:
import UIKit
import MapKit
class LocationSearchTable : UITableViewController {
var matchingItems:[MKMapItem] = []
var mapView: MKMapView? = nil
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
}
extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for 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.tableView.reloadData()
}
}
}
extension LocationSearchTable {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(matchingItems.count)
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
}
}
一旦matchingItems.count
不等于0,它就崩溃了,例如:
0 0 10 2016-10-20 15:43:53.914 ios-App [9137:977735] *断言 失败 - [UITableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3599.6/UITableView.m:8035 2016-10-20 15:43:53.927 ios-App [9137:977735] * 终止app到期 未被捕获的异常' NSInternalInconsistencyException',原因: ' UITableView(; layer =; contentOffset:{0, -64}; contentSize:{768,440}>)无法从其dataSource获取单元格
当我在cellForRowAtIndexPath中添加调试点时,它们永远不会到达,应用程序似乎在此之前崩溃了吗?
答案 0 :(得分:6)
错误
发生无法从其dataSource获取单元格
是因为cellForRowAtIndexPath
的签名错误。在Swift 3中它是
(override) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
并使用便捷方法
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath)
总是返回一个有效的非可选单元格。
PS:您不需要设置数据源并委托给self
因为UITableViewController
隐式执行此操作