使用 mapView 创建 tableViewCell

Creating a tableViewCell with a mapView

我正在创建一个内部有 mapView 的 tableViewCell。但是我似乎无法根据包含 tableView 的 viewController 中的位置添加注释。我通过设置 cell.location = orgObject.coordinate 在 cellForRowAtIndex 中开始,之后我将以下代码添加到我的自定义单元格中。但是 location 变量一直返回 nil。我猜这是因为 awakeForNibcellForRowAtIndexPath 被调用之前被调用了?我该如何解决?

import UIKit
import MapKit

class MapTableViewCell: UITableViewCell, MKMapViewDelegate {

  var location: CLLocation?
  @IBOutlet var mapView: MKMapView?



  override func awakeFromNib() {
      super.awakeFromNib()
      // Initialization code



      //MapView
      mapView!.showsPointsOfInterest = true
      if let mapView = self.mapView
      {
          mapView.delegate = self
      }


      let orgLocation = CLLocationCoordinate2DMake(location!.coordinate.latitude, location!.coordinate.longitude)

      let dropPin = MKPointAnnotation()
      dropPin.coordinate = orgLocation
      mapView!.addAnnotation(dropPin)

      self.mapView?.setRegion(MKCoordinateRegionMakeWithDistance(orgLocation, 500, 500), animated: true)


  }

  override func setSelected(selected: Bool, animated: Bool) {
      super.setSelected(selected, animated: animated)

      // Configure the view for the selected state
  }

}
override func awakeFromNib() {
      super.awakeFromNib()
      // Initialisation code

      //MapView
      mapView!.showsPointsOfInterest = true
      if let mapView = self.mapView
      {
          mapView.delegate = self
      }
}

从 cellForRowAtIndexPath

调用 cell.showLocation(location)
func showLocation(location:CLLocation) {
      let orgLocation = CLLocationCoordinate2DMake(location!.coordinate.latitude, location!.coordinate.longitude)

      let dropPin = MKPointAnnotation()
      dropPin.coordinate = orgLocation
      mapView!.addAnnotation(dropPin)
self.mapView?.setRegion(MKCoordinateRegionMakeWithDistance(orgLocation, 500, 500), animated: true)
}