【问题标题】:Annotation callout not working Swift注释标注不起作用Swift
【发布时间】:2017-08-30 11:27:06
【问题描述】:

我正在尝试在 MapKit 中为我的注释添加标注,但在网上搜索了很多之后我无法让它工作。

这就是我目前创建每个注释的方式,目前工作正常。

struct loc {
    let title: String
    let latitude: Double
    let longitude: Double
    let phone: Int
    //let subTitle: String
}

var locs = [
    loc(title: "New York, NY",    latitude: 40.713054, longitude: -74.007228, phone: 2334), //subTitle: "Sub title"),
    ]

func placeAnnotations() {
    let annotations = locs.map { location -> MKAnnotation in
        let annotation = MKPointAnnotation()
        annotation.title = location.title
        annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)

        //annotation.subtitle = location.subTitle
        return annotation
    }
    mapView.addAnnotations(annotations)
}

(我有一个将数据添加到数组 locs 的函数)

这就是我在尝试添加不起作用的标注时得到的结果。

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation { return nil }
    let identifier = "pin"
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView?.canShowCallout = true
        annotationView?.rightCalloutAccessoryView = UIButton(type: .infoDark)
    } else {
        annotationView?.annotation = annotation
    }

    return annotationView
}

【问题讨论】:

  • 您是否使用mapView.. 函数将mapView.delegate 设置为UIViewController
  • 不,我不认为我有,我只是试图这样做,但它最终崩溃了。我该如何正确地做到这一点?
  • 你应该mapView.delegate = self,为什么会崩溃?
  • 这就是我所做的,但我需要使用as! MKMapViewDelegate 进行投射。而且我不知道它为什么会崩溃,如果需要,我可以提供更多信息。
  • 你应该添加class MyViewController: MKMapViewDelegate .. {}

标签: ios swift swift3 mapkit mkannotationview


【解决方案1】:

你使用:

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!

那肯定不会被调用。在 Swift 3 中,正确的签名是:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?

【讨论】:

    猜你喜欢
    • 2014-08-14
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2020-10-09
    • 2012-09-19
    • 2015-09-14
    • 2017-08-20
    相关资源
    最近更新 更多