【问题标题】:Swift map pin callout and paramSwift 地图图钉标注和参数
【发布时间】:2019-04-01 01:14:54
【问题描述】:

我使用 MapKit 在我的 iOS 应用程序上制作了一张地图。

我使用标注按钮将我的图钉添加到我的视图中,该按钮在图钉弹出窗口中显示详细按钮。

此时,一切都很好,当我点击详细信息按钮时,我可以打印一些文本,呈现一个新的视图控制器,但我的问题是我无法弄清楚我如何知道我有哪个引脚轻拍。

我可以通过使用标题来解决它,但这对我来说不是最好的方法,我更喜欢使用我的项目 ID 而不是字符串。

如果有人知道如何在我的 pin 上添加“id”属性或使用 subtitle 属性(不在弹出气泡上显示),我将不胜感激 :)

感谢您的帮助。

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

    let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customAnnotation")
    annotationView.image = UIImage(named: "pin")
    annotationView.canShowCallout = true
    annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)

    return annotationView
}


func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl){

    print("OK, item tapped.")
}

【问题讨论】:

    标签: swift mapkit mkpinannotationview


    【解决方案1】:

    您可以继承MKPointAnnotation 以添加ID 属性

    class CustomPointAnnotation: MKPointAnnotation {
        let id: Int
    
        init(id: Int) {
            self.id = id
        }
    }
    

    用法

    let annotation = CustomPointAnnotation(id: INTEGER)
    annotation.coordinate = CLLocationCoordinate2D(latitude: DOUBLE, longitude: DOUBLE)
    mapView.addAnnotation(annotation)
    
    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        if let annotation = view.annotation as? CustomPointAnnotation {
            print("Annotation \(annotation.id)")
        }
    }
    

    您还可以通过扩展基本的MKAnnotation 协议来创建自己的注释类,如下所示:

    class CustomAnnotation: NSObject, MKAnnotation {
        let id: Int
        let coordinate: CLLocationCoordinate2D
    
        init(id: Int, latitude: Double, longitude: Double) {
            self.id = id
            self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        }
    }
    

    【讨论】:

    • 非常感谢!我几乎很好,我错过了 if let 声明!非常感谢您的回答!现在我很好! ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多