确定是否在Swift 2.0中拖动/移动了MKMapView

时间:2015-10-29 03:26:44

标签: ios swift mkmapview swift2

如何检测用户拖动或移动MKMapView的时间,以防止例如阻止用户当前位置的自动归位。

1 个答案:

答案 0 :(得分:14)

注意:这个答案是可能的,并且改编自Jano对Objective-C的相同问题的回答:determine if MKMapView was dragged/moved。谢谢Jano

要正确检测地图拖动,您必须添加UIPanGestureRecognizer。这是拖动手势识别器(平移=拖动)。

第1步:在viewDidLoad(Swift 2)中添加手势识别器

override func viewDidLoad() {
    super.viewDidLoad()
    // All your other setup code
    let mapDragRecognizer = UIPanGestureRecognizer(target: self, action: "didDragMap:")
    mapDragRecognizer.delegate = self
    self.mapView.addGestureRecognizer(mapDragRecognizer)
}

Swift 3版本的上述手势识别器设置(选择器语法已更改)

override func viewDidLoad() {
    super.viewDidLoad()
    let mapDragRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.didDragMap(gestureRecognizer:)))
    mapDragRecognizer.delegate = self
    self.mapView.addGestureRecognizer(mapDragRecognizer)
}



第2步:将协议UIGestureRecognizerDelegate添加到视图控制器,使其作为委托。

class MapViewController: UIViewController, UIGestureRecognizerDelegate

第3步:为UIPanGestureRecognizer添加以下代码,以便在MKMapView中使用现有的手势识别器:

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

第4步:如果您想要一次调用您的方法一次而不是每次拖动50次,请在选择器中检测“拖动结束”或“拖动开始”状态:

func didDragMap(gestureRecognizer: UIGestureRecognizer) {
    if (gestureRecognizer.state == UIGestureRecognizerState.Began) {
        print("Map drag began")
    }

    if (gestureRecognizer.state == UIGestureRecognizerState.Ended) {
        print("Map drag ended")
    }
}

希望这可以帮助有需要的人!