我已经设置了一个手势识别器,用于在用户点击文本字段外时解除键盘。 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设置断点,但它甚至没有被调用。
当我点击文本视图并打开键盘时,这是输出
keyboardFrameChanged
keyboardFrameChanged
will show
dismiss
当我点击其他任何东西(试图解除键盘)时,没有其他输出。
答案 0 :(得分:2)
将手势识别器委托给自己并添加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
。尝试使用此解决方案,否则当您检测到新的UITapGesture
时,您应该会失败表格视图的手势。
要使表格视图的UITapGestureRecognizer
失败,请使用以下代码:
if let recognizers = yourTableView.gestureRecognizers, let index = find(recognizers.map { $0 is UITapGestureRecognizer }, true) {
(recognizers[index] as! UIPanGestureRecognizer).requireGestureRecognizerToFail(keyboardDismissTapGesture)
}
也许不是最优雅的方式,但是当我想要失败 UIPanGestureRecognizer
时,它对我有用。我没有使用UITapGestureRecognizer
进行测试。
编辑:
if let recognizers = yourTableView.gestureRecognizers, let index = find(recognizers.map { $0 is UIGestureRecognizer }, true) {
(recognizers[index] as! UIGestureRecognizer).requireGestureRecognizerToFail(keyboardDismissTapGesture!)
}