拖动mapview时停止更新位置

时间:2016-11-11 14:32:47

标签: swift swift3 mapkit

我有一个mapview,他的更新位置。因此,如果我正在移动我的定位不断更新。 如果我拖动地图并尝试查看其他内容,我希望它停止。 我怎么能这样做?

我尝试了这个解决方案,以检测拖动地图的时间: Determine if MKMapView was dragged/moved in Swift 2.0

我在swift3工作。

1:在viewDidLoad中添加手势识别器:

    let mapDragRecognizer = UIPanGestureRecognizer(target: self, action: Selector(("didDragMap:")))
    mapDragRecognizer.delegate = self
    self.map.addGestureRecognizer(mapDragRecognizer)

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

 class MapViewController: UIViewController, UIGestureRecognizerDelegate
  1. 添加了其他代码:

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
    }
    
      func didDragMap(gestureRecognizer: UIGestureRecognizer) {
    if (gestureRecognizer.state == UIGestureRecognizerState.began) {
        print("Map drag began")
      self.locationManager.stopUpdatingLocation()
        }
    
    if (gestureRecognizer.state == UIGestureRecognizerState.ended) {
        print("Map drag ended")
    }
    }
    
  2. 如果我拖动地图,应用程序会崩溃。我得到了这个: "由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [app.ViewController didDragMap:]:无法识别的选择器发送到实例0x7fdf1fd132c0'" (..)" libc ++ abi.dylib:以NSException类型的未捕获异常终止"

1 个答案:

答案 0 :(得分:3)

Swift 3中的选择器语法已更改。您的手势识别器现在应如下所示:

let mapDragRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didDragMap))

func didDragMap(_ gestureRecognizer: UIGestureRecognizer) {
   if (gestureRecognizer.state == UIGestureRecognizerState.began) {
       print("Map drag began")
       self.locationManager.stopUpdatingLocation()
   }
   if (gestureRecognizer.state == UIGestureRecognizerState.ended) {
       print("Map drag ended")
   }
}

请注意,didDragMap(_:)是根据新的Swift API Design Guidelines

声明的

我还会用if语句替换你的switch语句,因为一旦有两个以上的情况,编译器就能够更好地优化它,并且更清楚。即。

func didDragMap(_ gestureRecognizer: UIGestureRecognizer) {
    switch gestureRecognizer.state {
    case .began:
        print("Map drag began")
        self.locationManager.stopUpdatingLocation()

    case .ended:
        print("Map drag ended")

    default:
        break
    }
}