我有一个带有 3D Touch 的 UITableView
Peek and Pop启用。我希望能够检测到用户何时查看 View 以及何时用户停止查看 View 而不弹出。我知道 previewingGestureRecognizerForFailureRelationship存在。我试过这样使用它:
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
// Here's where I add the gesture
let gesture = previewingContext.previewingGestureRecognizerForFailureRelationship
gesture.addObserver(self, forKeyPath: "state", options: .new, context: nil)
let sb = UIStoryboard(name: "Main", bundle: nil)
let detailVC = sb.instantiateViewController(withIdentifier: "SongPreviewViewController") as? SongPreviewViewController
return detailVC
}
然后我添加
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// can recognize peeking and canceling commit
if let object = object {
if keyPath == "state" {
let newValue = (change![NSKeyValueChangeKey.newKey]! as AnyObject).integerValue
let state = UIGestureRecognizerState(rawValue: newValue!)!
switch state {
case .possible:
print("switch - possible")
case .began:
print("switch - began")
case .changed:
print("switch - changed")
case .ended:
print("switch - ended")
case .cancelled:
print("switch - cancelled")
case .failed:
print("switch - failed")
}
}
}
}
但是每次 peek View 开始时,都会调用 .ended
。有谁知道如何正确执行此操作? Here's the reference I used for this code.感谢您的帮助!
最佳答案
UITapGestureRecognizer 仅在手势状态为 UIGestureRecognizerStateEnded 时触发,如以下链接所述:
About messages from UITapGestureRecognizer
所有手势识别器在可能状态(可能)中开始多点触摸序列。如果您希望获得最多两种状态:(.Possible) 和 < strong>(.end) 你可以试试这个代码(Xcode 版本 9.2,swift 3.2,目标 11.2)。
更改您的 addObserver 代码(添加了更多选项):
gesture.addObserver(self, forKeyPath: "state", options: [.prior, .old, .new], context: nil)
在您的 observeValue 方法中获取旧值和新值,如下所示。它将调用(.possible) 和(.end) 状态:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // can recognize peeking and canceling commit if let object = object { if keyPath == "state" { var newValue:Int? guard let change = change else { return } let old = change[.oldKey] == nil || change[.oldKey] as? NSNull != nil ? "nil" : "\(change[.oldKey]!)" let new = change[.newKey] == nil || change[.newKey] as? NSNull != nil ? "nil" : "\(change[.newKey]!)" if change[.notificationIsPriorKey] as? Bool == true { newValue = (old as AnyObject).integerValue } else { newValue = (new as AnyObject).integerValue } let state = UIGestureRecognizerState(rawValue: newValue!)! switch state { case .possible: print("switch - possible") case .began: print("switch - began") case .changed: print("switch - changed") case .ended: print("switch - ended") case .cancelled: print("switch - cancelled") case .failed: print("switch - failed") } } }
关于ios - 检测何时取消 3D Touch Peek 和 Pop View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49011170/