微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法使用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隐式执行此操作

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐