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


当前回答

这一定是通过触摸外部隐藏键盘的最简单方法:

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

(从如何解散键盘时,用户点击其他区域以外的文本框?)

其他回答

如果视图被嵌入到UIScrollView中,那么你可以使用以下方法:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

前者会在表格视图滚动时将键盘动画化,后者会像股票消息应用程序一样隐藏键盘。

注意,这些都可以在iOS 7.0或更高版本上使用。

发送消息resignFirstResponder的文本文件,把它放在那里。请参阅这篇文章了解更多信息。

所以我只需要解决这个问题,之前的答案都不适用。我的情况是:一个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
}

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

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

Or

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

https://github.com/michaeltyson/TPKeyboardAvoiding

这一定是通过触摸外部隐藏键盘的最简单方法:

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

(从如何解散键盘时,用户点击其他区域以外的文本框?)