我想知道如何使键盘消失时,用户触摸以外的UITextField。


当前回答

藏品视图:

// the keyboard follows the dragging touch off screen, and may be pulled upward again to cancel the dismiss
collectionView.keyboardDismissMode = .interactive
// dismisses the keyboard when a drag begins
collectionView.keyboardDismissMode = .onDrag

其他回答

这里有很多关于使用UITapGestureRecognizer的很好的答案——所有这些都打破了UITextField的clear (X)按钮。解决方案是通过它的委托来抑制手势识别器:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    BOOL touchViewIsButton = [touch.view isKindOfClass:[UIButton class]];
    BOOL touchSuperviewIsTextField = [[touch.view superview] isKindOfClass:[UITextField class]];
    return !(touchViewIsButton && touchSuperviewIsTextField);
}

这不是最可靠的解决方案,但对我来说很管用。

所以我只需要解决这个问题,之前的答案都不适用。我的情况是:一个UISearchBar,加上屏幕上的一些其他控件。我想在搜索栏之外点击键盘,但不传播到任何其他控件。当键盘被隐藏时,我希望所有的控制都能工作。

我做了什么:

1)在我的视图控制器中实现一个自定义触摸处理程序。

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    if searchBar.isFirstResponder()
    {
        // This causes the first responder, whoever it is, to resign first responder, and hide the keyboard.
        // We also "eat" the touch here and not allow it to propagate further.
        view.endEditing(true)
    }
    else
    {
        // OK to propagate the touch
        super.touchesBegan(touches, withEvent: event)
    }
}

2)添加了一对委托方法(我的是UISearchBar,但也有类似的UITextField)。下面代码中的controlContainerView是一个UIView,里面有一堆按钮。记住,在父视图上设置userInteractionEnabled会禁用它的所有子视图。

 func searchBarTextDidBeginEditing(searchBar: UISearchBar)
 {
     controlContainerView.userInteractionEnabled = false
     someButton.userInteractionEnabled = false
 }

 func searchBarTextDidEndEditing(searchBar: UISearchBar)
 {
     searchBar.resignFirstResponder()

    // Done editing: enable the other controls again.

    controlContainerView.userInteractionEnabled = false
    someButton.userInteractionEnabled = false
}

设置文本字段委托视图didload: 重载函数viewDidLoad() { super.viewDidLoad () self. usertext .delegate = self } 添加此函数: func textFieldShouldReturn(userText: UITextField! { userText.resignFirstResponder () 返回true; }

只是在这里添加我的版本如何在外部触摸时取消键盘。

viewDidLoad:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleTap];

在任何地方:

-(void)handleSingleTap:(UITapGestureRecognizer *)sender{
    [textFieldName resignFirstResponder];
    puts("Dismissed the keyboard");
}

在viewDidLoad 斯威夫特4.2 代码是这样的

let viewTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(dismissKeyboard))
        view.addGestureRecognizer(viewTap)
@objc func dismissKeyboard() {
        view.endEditing(true)
    }