我有一个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
添加了其他代码:
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")
}
}
如果我拖动地图,应用程序会崩溃。我得到了这个: "由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [app.ViewController didDragMap:]:无法识别的选择器发送到实例0x7fdf1fd132c0'" (..)" libc ++ abi.dylib:以NSException类型的未捕获异常终止"
答案 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
}
}