2016-11-11 50 views
1

我有一個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

    如果你顯示處理mapview的代碼,它會有所幫助。 – MwcsMac

    +0

    我已經更新了我的問題:)也許有更好的解決方案... –

    回答

    3

    選擇語法斯威夫特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 
        } 
    } 
    
    相關問題