【问题标题】:Adding action to MapKit annotation view in swift快速向 MapKit 注释视图添加操作
【发布时间】:2018-05-14 18:44:00
【问题描述】:

我在地图上的注释视图出现问题。我在地图上展示了我所有的宠物,就像他们的照片一样。当我点击任何注释时,我想去聊天屏幕。它的标识符“chatView”。我想我的代码是真的。但它不起作用。甚至,它没有打印出“Button tapped”。我该如何解决这个问题。这是代码

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

    if !(annotation is MKPointAnnotation) {
        return nil
    }
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "petIdentifier")
    if annotationView == nil {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "petIdentifier")
        annotationView!.canShowCallout = true
    }else {
        annotationView!.annotation = annotation
    }

    let pannotation : PPointAnnotation = annotation as! PPointAnnotation
    let petImage : UIImageView = UIImageView()
    petImage.frame = CGRect(x: -16, y: -4, width: 50, height: 50)
    petImage.layer.cornerRadius = 16
    petImage.layer.masksToBounds = true
    petImage.clipsToBounds = true
    petImage.backgroundColor = UIColor.white
    petImage.sd_setImage(with: URL(string: pannotation.photoURL as String), placeholderImage: UIImage(named: "map-e-giden.png"))
    annotationView?.addSubview(petImage)
    annotationView?.bringSubview(toFront: petImage)

    let button = UIButton(type: .detailDisclosure)
    annotationView?.rightCalloutAccessoryView = button
    return annotationView
}

func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
    if control == view.rightCalloutAccessoryView{
        print("button tapped")
        performSegue(withIdentifier: "chatView", sender: view)
    }
}

【问题讨论】:

  • 确保在设置地图视图后设置 MKMapViewDelegate。 mapView.delegate = self
  • @valosip 我确定

标签: swift annotations mapkit


【解决方案1】:

您不应使用addSubview 在注释上显示图像。

例如

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let reuseId = "petIdentifier"
    var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
    if pinView == nil {
        pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView?.canShowCallout = true
        pinView?.image = (downloaded image here) // e.g. SDWebImageManager.shared().loadImage(with: ...

        let rightButton: AnyObject! = UIButton(type: UIButtonType.detailDisclosure)
        pinView?.rightCalloutAccessoryView = rightButton as? UIView
    }
    else {
        pinView?.annotation = annotation
    }

    return pinView
}

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多