【问题标题】:didSelect mapView annotation not working properlydidSelect mapView 注释无法正常工作
【发布时间】:2018-01-25 02:51:46
【问题描述】:

当我点击地图注释时,它会显示有关该图钉的更多信息。

在我第一次点击尝试时,当我点击地图注释时,它会成功运行并显示正确的信息,但是当我点击返回按钮并第二次点击相同的引脚时,发生了致命错误,它说'在展​​开和可选值时意外发现 nil',

根据我的观察并进行了一些故障排除和调试,我发现致命错误仅在我没有先点击地图时才发生,然后我点击地图大头针,或者如果我不点击不同的大头针(如果我在第二次尝试时点击相同的引脚而不点击地图,则会发生第一个错误)

MyAnnotations班级:

import MapKit

class MyAnnotations: NSObject,MKAnnotation{

    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?
    var img: String?
    var court_id: Int?
    var class_name: String?

    init(coordinate:CLLocationCoordinate2D, title: String?, subtitle: 
    String?, img:String?, court_id: Int?, class_name: String?){
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
        self.img = img
        self.court_id = court_id
        self.class_name = class_name

        super.init()
    }
}

我的func mapView(_:didSelect:):

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
    let ibp = view.annotation as? MyAnnotations
    print(ibp!)
    ibp_id = (ibp?.court_id)!
    IdentifierCell = "pin_IBP"
    performSegue(withIdentifier: "map_ibp_info", sender: self)
}

【问题讨论】:

  • 哪一行显示“意外发现 nil”消息?如果它位于print(ibd!),那么您必须找出原因(例如print(view.annotation),如果不是您的自定义MyAnnotations [原文如此],请查看它是什么)。如果是court_id 的强制解包,你需要弄清楚它为什么是nil。但我们无法根据所提供的信息诊断问题,仅建议您 (a) 准确识别哪一行向您显示“意外发现 nil”消息; (b) 向后追溯以找出可能发生的情况(毫无疑问,在此处未包含的代码中)。
  • 是的,它来自print(ibd!)
  • 所以print(view.annotation) 看看那是什么。看看演员为何失败。
  • @Rob
  • 这意味着您点击了用户位置。所以在开头添加一行if view.annotation is MKUserLocation { return }。基本上,如果它是MKUserLocation,就告诉它立即返回。或者你可以使用guard let ibp = view.annotation as? MyAnnotations else { return },如果不是MyAnnotations,则退出。

标签: ios mkmapview swift4 mkannotation mkannotationview


【解决方案1】:

尝试以下代码:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
    if view.annotation is MKUserLocation {
        return
    }

    let ibp = view.annotation as? MyAnnotations
    print(ibp!)
    ibp_id = (ibp?.court_id)!
    IdentifierCell = "pin_IBP"
    performSegue(withIdentifier: "map_ibp_info", sender: self)
}

【讨论】:

  • Unexpected non-void return value in void function
  • 是的,我已经从 nil 中发现了它,与 @Rob 先生的回答相同
  • 先生,我还有一个问题,如果标题仍然显示,我无法再次点击地图图钉,如何在标题仍在显示时再次点击地图图钉?
  • the title is still showing 表示以某种方式选择了注释。然后,当您再次单击它时,didSelect 函数不会触发,因为它“已被选中”。完成所需操作后,您必须通过调用 mapView.deselectAnnotation(view.annotation, animated: true) 手动取消选择注释。
猜你喜欢
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 1970-01-01
  • 2012-01-31
相关资源
最近更新 更多