确定是否在Swift 2.0中拖动/移动了MKMapView [英] Determine if MKMapView was dragged/moved in Swift 2.0

查看:169
本文介绍了确定是否在Swift 2.0中拖动/移动了MKMapView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I detect when the user has dragged or move an MKMapView in order to, e.g., prevent automatic homing in on the user's current location.

推荐答案

注意:这个答案是可能的,并且改编自Jano对Objective-C相同问题的回答:确定是否拖动/移动了MKMapView 。感谢 Jano

Note: This answer was made possible and was adapted from Jano's response to the same question for Objective-C here: determine if MKMapView was dragged/moved. Thanks Jano.

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

To properly detect a map drag you have to add a UIPanGestureRecognizer. This is the drag gesture recognizer (panning = dragging).

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

Step 1: Add the gesture recognizer in 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版本的上述手势识别器设置(选择器语法已更改)

Swift 3 version of above gesture recognizer setup (selector syntax has changed)

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




第2步:添加协议UIGestureRecognizerDelegate到视图控制器,所以它作为委托。



Step 2: Add the protocol UIGestureRecognizerDelegate to the view controller so it works as delegate.

class MapViewController: UIViewController, UIGestureRecognizerDelegate

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

Step 3: Add the following code for the UIPanGestureRecognizer to work with the already existing gesture recognizers in MKMapView:

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

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

Step 4: In case you want to call your method once instead 50 times per drag, detect either the "drag ended" or "drag began" state in your selector:

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

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

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

Hope this helps someone in need!

这篇关于确定是否在Swift 2.0中拖动/移动了MKMapView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆