需求:点击地图空白处(没有选中任何 MKAnnotationView), 实现一些特殊的功能;
实现:添加自定义的UITapGestureRecognizer手势
推荐方案二
方案一
override func viewDidLoad() {
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(mapViewTapAction))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
tapGesture.delegate = self
mapView.addGestureRecognizer(tapGesture)
}
@objc fileprivate func mapViewTapAction(_ sender: Any) {
guard let tapGesture = sender as? UITapGestureRecognizer else {
return
}
let point = tapGesture.location(in: tapGesture.view)
guard let annotionView = mapView.hitTest(point, with: nil) as? MKAnnotationView else {
for selectedAnnotation in mapView.selectedAnnotations {
mapView.deselectAnnotation(selectedAnnotation, animated: true)
}
return
}
selectedAnnotionView(annotionView)
}
private func selectedAnnotionView(_ view: MKAnnotationView) {
view.setSelected(true, animated: true) //这句也可以不要, 因为点击的时候同时 didSelected 也响应了
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseIdentifier = CustomAnnotationView.getAnnotationViewId()
let annotationView: CustomAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? CustomAnnotationView ?? CustomAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
annotationView.isEnabled = false //false: 不会响应 didSelect 和 didDeselect
return annotationView
}
方案二
override func viewDidLoad() {
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(mapViewTapAction))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
tapGesture.delegate = self
mapView.addGestureRecognizer(tapGesture)
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
//do somthing
}
@objc fileprivate func mapViewTapAction(_ sender: Any) {
guard let _ = sender as? UITapGestureRecognizer else {
return
}
//do somthing
}
//UIGestureRecognizerDelegate
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let point = gestureRecognizer.location(in: gestureRecognizer.view)
guard let _ = mapView.hitTest(point, with: nil) as? MKAnnotationView else {
return true
}
return false
}