我将以下 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
}
}
![enter image description here](https://i.stack.imgur.com/pKskF.png)
![enter image description here](https://i.stack.imgur.com/28oTA.png)
在这里它崩溃了一次matchingItems.count
不等于 0 例如:
0 0 10 2016-10-20 15:43:53.914 ios-应用程序[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 应用程序[9137:977735] *终止应用程序到期
未捕获异常“NSInternalInconsistencyException”,原因:
'UITableView(;层=;contentOffset:{0,
-64}; contentSize: {768, 440}>) 未能从其数据源获取单元格
当我在 cellForRowAtIndexPath 中添加调试点时,它们永远不会到达,应用程序似乎在此点之前崩溃?
错误
无法从其数据源获取单元格
发生的原因是签名cellForRowAtIndexPath
是错的。在 Swift 3 中是
(override) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
并使用便捷方法
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath)
它始终返回一个有效的非可选单元格。
PS:您不需要设置数据源和委托self
因为UITableViewController
隐含地这样做
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)