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


当前回答

这是一个很好的通用解决方案:

objective - c:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];    
}

迅速:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

基于@icodebuster解决方案:https://stackoverflow.com/a/18756253/417652

其他回答

我发现有些人在使用UITapGestureRecognizer方法时遇到了问题。我在保持现有按钮点击行为不变的情况下完成这一功能的最简单方法是只添加一行到@Jensen2k的答案:

[tap setCancelsTouchesInView:NO];

这使得我现有的按钮仍然可以工作,而不需要使用@Dmitry Sitnikov的方法。

在这里阅读有关属性(搜索CancelsTouchesInView): UIGestureRecognizer类引用

我不确定它将如何与滚动条一起工作,因为我看到有些人有问题,但希望其他人可能会遇到与我相同的情况。

这里有很多关于使用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);
}

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

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch = touches.first{
     view.endEditing(true)

     }
}

看看这个,这是最简单的方法,

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
      [self.view endEditing:YES];// this will do the trick
}

Or

这个库将处理包括滚动条自动滚动,点击空间隐藏键盘等…

https://github.com/michaeltyson/TPKeyboardAvoiding

最好是让你的UIView成为UIControl的一个实例(在界面构建器中),然后连接他们的TouchUpInside事件来解散键盘方法。这个IBAction方法看起来像:

- (IBAction)dismissKeyboard:(id)sender {
    [aTextBox resignFirstResponder];
}