swift - Swift 地图图钉标注和参数
问题描述
我使用 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.")
}
解决方案
您可以子类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)
}
}
推荐阅读
- jspdf-autotable - 带有 CSS 样式的 HTML 表格的 Autotable
- windows - 如何将文件删除到 shell:从 vbs 启动?
- http-headers - PowerQuery 中 SSO/MFA 的成本真的这么高吗,或者这只是微软的怪癖?
- java - 当我有两个@Bean 时,我应该把@Qualifier 放在哪里?
- excel - 使用 ActiveX 组合框中的值的公式未更新
- java - 使用 data-* 属性(HtmlUnit)从 span 元素中获取数据
- javascript - Tampermonkey 中的状态操作
- azure-active-directory - 如何从用户管理的身份显式授予对 AAD 应用程序注册的访问权限?
- c# - 从 DI 容器中注册具有多种类型的通用动作过滤器
- gnome - 如何重新禁用 gnome-shell 40 中的热角?