我尝试从tableView单元格的地址转换为mapView并在 Map 上显示引脚 .
我确信我的代码中的所有内容都不是零 .
但是Xcode说我的 oldValue
是 nil
(在 didSet{}
中) . 我不知道如何解决它 .
以下是我的代码:
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView! {
didSet {
mapView.mapType = .Standard
mapView.delegate = self
}
}
var location:CLLocation? {
didSet {
clearWayPoints()
if location != nil {
println(location!.coordinate.longitude)
let coordinate = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let pin = MapPin(coordinate: coordinate, title: "Current", subtitle: "here")
setAnnotation(pin)
}
}
}
private func clearWayPoints() {
if mapView?.annotations != nil {
mapView.removeAnnotations(mapView.annotations as [MKAnnotation])
}
}
func setAnnotation(pin: MKAnnotation) {
mapView.addAnnotation(pin)
mapView.showAnnotations([pin], animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
var view = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.AnnotationViewReuseIdentifier)
if view == nil {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.AnnotationViewReuseIdentifier)
view.canShowCallout = true
} else {
view.annotation = annotation
}
return view
}
struct Constants {
static let AnnotationViewReuseIdentifier = "map cell"
}
}
我的模型只是 var location:CLLocation?
,我从我的segue更新了这个值 .
我确信我在println()中得到了正确的坐标 .
但Xcode总是说
致命错误:在展开Optional值时意外发现nil
我发现 nil
似乎是 oldValue=(CLLocation?)nil
!
以下是我的简单类 MapPin
,它实现 MKAnnotation
class MapPin: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
1 回答
我刚刚遇到了完全相同的问题并修复了它!您正在尝试将注释添加到尚未初始化的
mapView
.问题是你在
prepareForSegue:
中设置location
. 此时你的mapView
是零 . 在viewDidLoad:
中调用mapView.addAnnotation:
来修复它 .我猜这就是为什么它说“加载视图的任何其他设置 after ” . 因为那时你的所有商店都被初始化了 .
希望这可以帮助!