我将以下 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] * Assertion failure in -[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] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (; layer = ; contentOffset: {0, -64}; contentSize: {768, 440}>) failed to obtain a cell from its dataSource
当我在 cellForRowAtIndexPath 中添加调试点时,它们从未到达,应用程序似乎在此点之前崩溃了?
最佳答案
错误
failed to obtain a cell from its dataSource
发生是因为cellForRowAtIndexPath
的签名错误。在 Swift 3 中是
(override) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
并使用便捷的方法
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath)
它总是返回一个有效的非可选单元格。
PS:您不需要将数据源和委托(delegate)设置为 self
,因为 UITableViewController
会隐式执行此操作
关于swift - 无法使用 swift 3 从其数据源获取单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40157812/