手势识别器不叫
当用户在文本框之外轻击时,我已经设置了一个用于解除键盘的手势识别器。 DismissKeyboard
函数不会被调用。
我是否设置了观察者错误还是这是一个不同的问题? 另外,这是一个正在挖掘的桌面视图。
代码摘录
class CommentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) } func keyboardFrameChanged(notification: NSNotification) { println("keyboardFrameChanged") let userInfo = notification.userInfo let key = UIKeyboardFrameEndUserInfoKey if let info = userInfo { let frameValue = info[key] as! NSValue let _frame = frameValue.CGRectValue() } } func keyboardWillShow(notification: NSNotification) { if keyboardDismissTapGesture == nil { println("dismiss") keyboardDismissTapGesture = UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard:")) self.view.addGestureRecognizer(keyboardDismissTapGesture!) } } func keyboardWillHide(notification: NSNotification) { if keyboardDismissTapGesture != nil { println("test2") self.view.removeGestureRecognizer(keyboardDismissTapGesture!) keyboardDismissTapGesture = nil } } func dismissKeyboard(sender: AnyObject) { println("dismiss keyboard") commentTextField.resignFirstResponder() }
我在dismissKeyboard中设置了一个断点,但它甚至没有被调用。
产量
当我点击textview和键盘打开,这是输出
keyboardFrameChanged keyboardFrameChanged will show dismiss
当我点击其他任何东西(试图解除键盘),没有进一步的输出。
将手势识别器委托设置为您自己并添加UIGestureRecognizerDelegate
协议。
func keyboardWillShow(notification: NSNotification) { if keyboardDismissTapGesture == nil { println("dismiss") keyboardDismissTapGesture = UITapGestureRecognizer(target: view, action: "dismissKeyboard:") keyboardDismissTapGesture.delegate = self self.view.addGestureRecognizer(keyboardDismissTapGesture!) } }
然后加:
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true }
我的猜测是,你的表格视图的手势正在干扰新的UITapGesture
。 试试这个解决scheme,否则当你检测到新的UITapGesture
时,你应该会失败你的表视图的手势。
为了使表视图的UITapGestureRecognizer
失败,我使用下面的代码:
if let recognizers = yourTableView.gestureRecognizers, let index = find(recognizers.map { $0 is UITapGestureRecognizer }, true) { (recognizers[index] as! UIPanGestureRecognizer).requireGestureRecognizerToFail(keyboardDismissTapGesture) }
也许不是最优雅的做法,但是当我想要失败UIPanGestureRecognizer
时,它适用于我。 我还没UITapGestureRecognizer
进行testing。
编辑:
if let recognizers = yourTableView.gestureRecognizers, let index = find(recognizers.map { $0 is UIGestureRecognizer }, true) { (recognizers[index] as! UIGestureRecognizer).requireGestureRecognizerToFail(keyboardDismissTapGesture!) }