gpt4 book ai didi

swift - 拖动 map View 时停止更新位置

转载 作者:搜寻专家 更新时间:2023-11-01 06:36:49 26 4
gpt4 key购买 nike

我有一个 map View ,其中包含他的更新位置。因此,如果我移动,我的定位会不断更新。如果我拖动 map 并尝试在其上查看其他内容,我希望它停止。我该怎么做?

我试过这个解决方案,来检测 map 何时被拖动: 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:将协议(protocol) UIGestureRecognizerDelegate 添加到 View Controller ,使其作为委托(delegate)工作。

 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")
    }
    }

如果我拖动 map ,应用程序会崩溃。我得到了这个:“由于未捕获的异常‘NSInvalidArgumentException’而终止应用程序,原因:‘-[app.ViewController didDragMap:]: 无法识别的选择器发送到实例 0x7fdf1fd132c0’”(..)“libc++abi.dylib:以 NSException 类型的未捕获异常终止"

最佳答案

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 声明的

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

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

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

default:
break
}
}

关于swift - 拖动 map View 时停止更新位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com