Prevent scrolling in a MKMapView, also when zooming

前端 未结 6 485
借酒劲吻你
借酒劲吻你 2020-12-03 03:09

The scrollEnabled seems to be breakable once the user starts pinching in a MKMapView.

You still can\'t scroll with one finger, but if y

6条回答
  •  青春惊慌失措
    2020-12-03 03:51

    I tried this and it works.

    First create a property:

    var originalCenter: CLLocationCoordinate2D?
    

    Then in regionWillChangeAnimated, check if this event is caused by a UIPinchGestureRecognizer:

    func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
        let firstView = mapView.subviews.first
        if let recognizer = firstView?.gestureRecognizers?.filter({ $0.state == .Began || $0.state == .Ended }).first as? UIPinchGestureRecognizer {
            if recognizer.scale != 1.0 {
                originalCenter = mapView.region.center
            }
        }
    }
    

    Then in regionDidChangeAnimated, return to original region if a pinch gesture caused the region changing:

    func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        if let center = originalCenter {
            mapView.setRegion(MKCoordinateRegion(center: center, span: mapView.region.span), animated: true)
            originalCenter = nil
            return
        }
    // your other code 
    }
    

提交回复
热议问题