2017-08-08 14 views
0

Xcodeは、テーブルビューがデータソースからセルを取得できなかったというエラーを返しました。私は検索バーを使用して検索用語を入力し、それをテーブルビューの下に表示させます。データソースからセルを取得できませんでしたか?

私の最初の考えは、セル識別子をcellと正しく設定していることを確認することでしたが、これは正しいですが、このコードでは別のものがあると思います。必要に応じて残りのコードを追加することができますが、ここで最初に何か不足しているかどうかを確認したいだけです。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("cell")! 
     let selectedItem = searchedItems[indexPath.row].placemark 
     cell.textLabel?.text = selectedItem.name 
     cell.detailTextLabel?.text = "" 
     return cell 
    } 
} 

2つのビューコントローラからフルコードを追加するための編集。これまでの目的は、ユーザの位置を取得してから、検索用語を入力することである。ターゲット]をクリックし、検索結果を表ビューに表示します。

最初のビューコントローラ

import UIKit 
import MapKit 
import CoreLocation 

class ViewController: UIViewController { 

    //this variable is for access to the location manager throughout the scope of the controller 
    let locationManager = CLLocationManager() 

    @IBOutlet weak var mapView: MKMapView! 

    var resultSearchController:UISearchController? = nil 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestWhenInUseAuthorization() //this triggers authorization alert - one time only 
     locationManager.requestLocation() //triggers an also one time location request 

     let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable 
     resultSearchController = UISearchController(searchResultsController: locationSearchTable) 
     resultSearchController?.searchResultsUpdater = locationSearchTable 


     //configure the search bar and embed within the navigation bar 
     let searchBar = resultSearchController!.searchBar 
     searchBar.sizeToFit() 
     searchBar.placeholder = "Search for places" 
     navigationItem.titleView = resultSearchController?.searchBar 

     //configure the UISearchController appearance 
     resultSearchController?.hidesNavigationBarDuringPresentation = false //ensure search bar is accessible at all times 
     resultSearchController?.dimsBackgroundDuringPresentation = true //for when search bar is selected 
     definesPresentationContext = true 

     locationSearchTable.mapView = mapView //passes along a handle of the mapView from the main VC onto the locationSearchTable 

    } 

} 

//extension used for code organization to group delegate methods 

extension ViewController : CLLocationManagerDelegate { 

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 
     if status == .authorizedWhenInUse { //is user responded with allow 
      locationManager.requestLocation() //essentially requesting on the double as first is a permission failure before allow is pressed 
     } 
    } 

    //gets called when location information comes back. You get an array of locations but only interested in first item. Eventually will zoom to this location 
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

     if let location = locations.first { 
      let span = MKCoordinateSpanMake(0.05, 0.05) //span is the zoom level set at arbitrary level for now 
      let region = MKCoordinateRegionMake(location.coordinate, span) 
      //once you combine coordinate and span into a region you can zoom using setRegion(_:animated:) 
      mapView.setRegion(region, animated: true) 
     } 
    } 

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 
     print("error:: (error)") 
    } 

} 

第二ビューコントローラ

import UIKit 
import MapKit 


class LocationSearchTable : UITableViewController { 

    var matchingItems:[MKMapItem] = [] //for stashing search results for easy access 
    var mapView: MKMapView? = nil //search queries rely on map region for local results. This is ahandle to the map from the previous screen 



    //this method converts the placemark to a custom address format like: "4 Melrose Place, Washington DC" 

    func parseAddress(selectedItem:MKPlacemark) -> String { 
     // put a space between "4" and "Melrose Place" 
     let firstSpace = (selectedItem.subThoroughfare != nil && selectedItem.thoroughfare != nil) ? " " : "" 
     // put a comma between street and city/state 
     let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) && (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : "" 
     // put a space between "Washington" and "DC" 
     let secondSpace = (selectedItem.subAdministrativeArea != nil && selectedItem.administrativeArea != nil) ? " " : "" 
     let addressLine = String(
      format:"%@%@%@%@%@%@%@", 
      // street number 
      selectedItem.subThoroughfare ?? "", 
      firstSpace, 
      // street name 
      selectedItem.thoroughfare ?? "", 
      comma, 
      // city 
      selectedItem.locality ?? "", 
      secondSpace, 
      // state 
      selectedItem.administrativeArea ?? "" 
     ) 
     return addressLine 
    } 

} 

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 { //executes the search query 
      response, _ in guard let response = response else { 
       return 
      } 
      self.matchingItems = response.mapItems 
      self.tableView.reloadData() 
     } 
    } 


} 
+0

セルはどのように定義されていますか。それはコードですか?あなたはtableviewでセル識別子を登録しましたか?各行で何が起きているのかを確認するためにこのコードを踏んだことがありますか? – Abizern

+0

セルを登録することを忘れてはなりません。 – Ryan

+0

セル識別子を登録することによって、単にテーブルビューでセル識別子の名前を設定することを意味しますか?もしそうなら、私は属性インスペクタでこれを行いました。それとも別のことを意味しましたか?セルは、ストーリーボードのテーブルビューからのプロトタイプです。 – cheznead

答えて

0

2つのこと。

  1. 正しいデータソースが割り当てられていることを確認してください。

  2. あなたがデータソースにUITableViewのデータソースを記述していることを確認してください。 UITableViewDataSourceのようなものYourViewController : UITableViewDataSource

+0

このクラスはUITableViewControllerを継承しているので、データソースプロトコルに準拠することは冗長です。私はチュートリアルに従っているので、すべてのコードを投稿して、私のために多くの新しい場面をカバーしています。 – cheznead

関連する問題