无法使用swift 3从其dataSource获取单元格

前端之家收集整理的这篇文章主要介绍了无法使用swift 3从其dataSource获取单元格前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我将下面的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

enter image description here

一旦matchItems.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:您不需要设置datasource和委托给self,因为UITableViewController隐式执行此操作

猜你在找的Swift相关文章