在MKAnnotationView上显示上下文菜单



我希望能够在直接点击MKAnnotationView时显示上下文菜单,除了callout附件视图。

例如

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
let FirstAction = UIAction(title: "First Action"),
handler: {_ in
print("First action")
})

let secondAction = UIAction(title: "Second Action",
handler: {_ in
print("Second action")
})

let button = UIButton(type: .detailDisclosure)
button.menu = UIMenu(title: "My Title"                               
children: [firstAction, secondAction])
button.showsMenuAsPrimaryAction = true
view.canShowCallout = true
view.rightCalloutAccessoryView = button
}

然后在calloutAccessoryControlTapped中,我想执行与点击显示上下文菜单(UIMenu)rightCalloutAccessoryView (UIButton)相同的操作。我想也许这能奏效

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
control.sendActions(for: .primaryActionTriggered)
}

,但这不起作用。也许我是通过错误的EventsendActions()?或者这根本不可能?无论如何,任何帮助都是非常感谢的。

你可以使用iOS 15提供的changesSelectionAsPrimaryActionapi来显示菜单作为按钮选择的主要操作,添加

button.changesSelectionAsPrimaryAction = true