手势识别器在一段时间后无响应

时间:2017-08-16 01:33:16

标签: ios swift uigesturerecognizer

我有一个UILongPressGestureRecognizer似乎在一段时间后没有响应。它似乎与时间的推移有关,可能与失去活跃状态并进入后台的应用程序相关。

当我第一次重新打开应用程序并尝试长按或滑动时,我经常会遇到这个问题。如果我转到另一个视图控制器然后返回,则重新加载会导致手势识别器再次开始工作!

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

有关处理手势识别器的任何想法都会变得没有反应吗?

1 个答案:

答案 0 :(得分:0)

尝试以下方法。

  1. longpress设为全局变量
  2. viewWillAppear中添加手势(如果不存在)
  3. viewWillAppear
  4. UIApplicationWillEnterForeground中添加通知
  5. 删除viewWillDisappear
  6. 中的手势和通知

    像这样的东西

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