我尝试从 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 总是说
fatal error: unexpectedly found nil while unwrapping an Optional value
我发现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
添加注释。
问题是您在 prepareForSegue:
中设置location
。此时,您的 mapView
为零。在viewDidLoad:
中调用mapView.addAnnotation:
来修复它。
我想这就是为什么它说“加载 View 后进行任何其他设置”。因为这样你所有的导出都被初始化了。
希望这有帮助!
关于ios - mapView.addAnnotation() 说 "unexpectedly found nil while unwrapping an Optional value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29892797/