【发布时间】:2021-04-24 04:33:58
【问题描述】:
我创建了一个UIViewRepresantable 来在 SwiftUI 中显示地图。一旦点击注释,我想显示一个 ActionSheet。在Coordinator 内部,我正在尝试使用calloutAccessoryControlTapped 方法。现在我只是想打印“注释被点击”但是这不起作用。有人知道我可能会错过什么吗?
struct MapModel: UIViewRepresentable {
let view = UIView()
let map = MKMapView()
let yedikuleShelter = ShelterAnnotation(title: "Yedikule Hayvan Barınağı", coordinate: CLLocationCoordinate2D(latitude: 40.9907822322955, longitude: 28.920995484659933))
func makeUIView(context: Context) -> UIView {
view.addSubview(map)
map.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
map.widthAnchor.constraint(equalTo: view.widthAnchor),
map.heightAnchor.constraint(equalTo: view.heightAnchor),
map.centerXAnchor.constraint(equalTo: view.centerXAnchor),
map.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
return view
}
class MapViewCoordinator: NSObject, MKMapViewDelegate {
var mapModelController: MapModel
init(_ control: MapModel) {
self.mapModelController = control
}
func mapView(_ mapView: MKMapView, viewFor
annotation: MKAnnotation) -> MKAnnotationView?{
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customView")
//Custom Image Icon
annotationView.image = #imageLiteral(resourceName: "AnbulancePin")
annotationView.frame.size = CGSize(width: 50, height: 50)
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
let btn = UIButton(type: .detailDisclosure)
view.canShowCallout = true
view.rightCalloutAccessoryView = btn
}
//Display alert once annotation is tapped
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
print("annotation is tapped")
}
}
class ShelterAnnotation: NSObject, MKAnnotation {
let title: String?
let coordinate: CLLocationCoordinate2D
init(title: String?,
coordinate: CLLocationCoordinate2D) {
self.title = title
self.coordinate = coordinate
}
}
func updateUIView(_ uiView: UIView, context: Context) {
let coordinate = CLLocationCoordinate2D(latitude: 41.01224, longitude: 28.976018)
let span = MKCoordinateSpan(latitudeDelta: 0.7,
longitudeDelta: 0.7)
map.setRegion(MKCoordinateRegion(center: coordinate,
span: span),
animated: true)
map.delegate = context.coordinator
map.addAnnotation(yedikuleShelter)
}
func makeCoordinator() -> MapViewCoordinator {
MapViewCoordinator(self)
}
}
【问题讨论】:
-
您必须在此处绑定布尔变量并在“didSelect”函数中使其为真。或者您可以使用函数类型变量,例如 let action: () -> Void 并使用它
标签: swift swiftui annotations mapkit mkannotation