MKMapView和自定义的UITapGestureRecognizer的冲突

需求:点击地图空白处(没有选中任何 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
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容