我有一个UILongPressGestureRecognizer似乎在一段时间后没有响应。它似乎与时间的推移有关,可能与失去活跃状态并进入后台的应用程序相关。
当我第一次重新打开应用程序并尝试长按或滑动时,我经常会遇到这个问题。如果我转到另一个视图控制器然后返回,则重新加载会导致手势识别器再次开始工作!
let longpress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPressGestureRecognized(_:)))
mainView.addGestureRecognizer(longpress)
有关处理手势识别器的任何想法都会变得没有反应吗?
答案 0 :(得分:0)
尝试以下方法。
longpress
设为全局变量viewWillAppear
中添加手势(如果不存在)viewWillAppear
UIApplicationWillEnterForeground
中添加通知
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)
}
}