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
}
}
编辑以从两个视图控制器添加完整代码。到目前为止的目的是获得用户的位置,然后能够输入搜索词,例如,在搜索栏中定位目标,并在表格视图中显示搜索结果。
第一视图控制器
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 :(得分:0)
两件事。
确保您已分配正确的数据源。
确保您在数据源中说过它是UITableView的数据源。它符合UITableViewDataSource
YourViewController : UITableViewDataSource
醇>