Ios addAnnotation()表示;在展开可选值“时意外发现nil”;
我尝试从tableView单元格的地址切换到mapView,并在地图上显示pin 我确信我的代码中并不是什么都是零 但是Xcode说我的Ios addAnnotation()表示;在展开可选值“时意外发现nil”;,ios,swift,mkmapview,mkannotation,null,Ios,Swift,Mkmapview,Mkannotation,Null,我尝试从tableView单元格的地址切换到mapView,并在地图上显示pin 我确信我的代码中并不是什么都是零 但是Xcode说我的oldValue是nil(在didSet{})。我不知道怎么修理它 以下是我的代码: class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! { didSet { m
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总是说
致命错误:在展开可选值时意外发现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
}
}
我只是有完全相同的问题,并解决了它!您正在尝试将注释添加到尚未初始化的
mapView
问题是您正在prepareforsgue:
中设置位置。此时,您的mapView
为零。在viewDidLoad:
中调用mapView.addAnnotation:
来修复它
我想这就是为什么它会说“在加载视图后执行任何附加设置”的原因,因为这样所有的插座都会初始化
希望这有帮助