在MapKit的注释内是否可以链接?
我希望可以通过单击“显示更多”-链接(但仅在单击时)在此气泡内显示更多文本,这些文本在单击注释时显示。 否则只会显示批注的标题。
答案 0 :(得分:1)
我们将使用MKAnnotationView
的以下子类来添加注释,如下所示:
class CustomAnnotation: MKPointAnnotation {
var isCollapsed = true // current state
// set true when user taps the link to expand/collapse annotation-view
var setNeedsToggle = false
}
let annotation = CustomAnnotation()
annotation.coordinate = self.mapView.centerCoordinate
annotation.title = "Annotation Title"
mapView.addAnnotation(annotation)
在viewForAnnotation
中,我们使用detailCalloutAccessoryView
和rightCalloutAccessoryView
来显示描述并切换链接,如下所示:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let annot = annotation as? CustomAnnotation else { return nil }
// Initialize AnnotationView
var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: "AnID")
if (annotationView == nil) {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "AnID")
annotationView.canShowCallout = true
} else {
annotationView.annotation = annotation
}
// Expand/Collapse Button
let rightButton = UIButton(type: .detailDisclosure)
rightButton.setImage(UIImage(named: annot.isCollapsed ? "ic_showmore" : "ic_showless"), for: .normal)
annotationView.rightCalloutAccessoryView = rightButton
// Description View
if (annot.isCollapsed) {
annotationView.detailCalloutAccessoryView = nil
} else {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
label.text = "A longer description in place to be shown when the accessory view is tapped"
label.font = UIFont.italicSystemFont(ofSize: 14.0)
label.numberOfLines = 0
annotationView.detailCalloutAccessoryView = label
label.widthAnchor.constraint(lessThanOrEqualToConstant: label.frame.width).isActive = true
label.heightAnchor.constraint(lessThanOrEqualToConstant: 90.0).isActive = true
}
return annotationView
}
点击链接时会触发 calloutAccessoryControlTapped
事件,因此我们展开/折叠注释视图,如下所示:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
guard let oldAnnot = view.annotation as? CustomAnnotation else { return }
let annotation = CustomAnnotation()
annotation.coordinate = oldAnnot.coordinate
annotation.title = oldAnnot.title
annotation.setNeedsToggle = true
if (oldAnnot.isCollapsed) {
annotation.isCollapsed = false
}
mapView.removeAnnotation(oldAnnot)
mapView.addAnnotation(annotation)
}
最后,我们检查setNeedsToggle
是否为真,因此我们显示展开/折叠的注释视图,如下所示:
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
for view in views {
if let annotation = view.annotation as? CustomAnnotation, annotation.setNeedsToggle {
mapView.selectAnnotation(annotation, animated: true)
return
}
}
}
以下是展开/折叠视图: