2017-08-16 39 views
0

我有一段時間後似乎無響應的UILongPressGestureRecognizer。它似乎與時間流逝相關,並且可能與失去活動狀態並進入背景的應用相關。手勢識別器在時間後無響應

我經常遇到問題,當我第一次重新打開應用程序,並嘗試長按或刷卡,既沒有工作。如果我轉到不同的視圖控制器然後返回,那麼重新加載會導致手勢識別器再次開始工作!

let longpress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPressGestureRecognized(_:))) 
    mainView.addGestureRecognizer(longpress) 

圍繞處理手勢識別器變得沒有響應這樣的任何想法?

+1

你做了什麼像禁用userInteraction或刪除手勢在viewWillDisappear或viewDidDisappear? –

+0

在哪個方法中執行'mainView.addGestureRecognizer(longpress)'? – Hooda

+0

你可以添加更多的代碼 - 至少是你設置它的方法。 –

回答

0

請嘗試以下方法。

  1. longpress一個全局變量
  2. viewWillAppear添加手勢,如果它不存在
  3. viewWillAppear添加通知UIApplicationWillEnterForeground
  4. 中刪除手勢和通知viewWillDisappear

像這樣的東西

var longpress: UILongPressGestureRecognizer! 

override viewDidLoad() { 
    super.viewDidLoad 
    longpress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPressGestureRecognized(_:))) 
} 

override viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 
    checkGestureAvailability() 
    NotificationCenter.default.addObserver(self, selector: #selector(checkGestureAvailability), name: Notification.Name.UIApplicationWillEnterForeground, object: nil) 
} 

override viewWillDisappear(_ animated: Bool) { 
    if mainView.gestureRecognizers.contains(longpress) { 
     mainView.removeGestureRecognizer(longpress) 
    } 
    NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillEnterForeground, object: nil) 
    super.viewWillDisappear(animated) 
} 

func checkGestureAvailability() { 
    if !mainView.gestureRecognizers.contains(longpress) { 
     mainView.addGestureRecognizer(longpress) 
    } 
}