ios 按下 UISearch Bar“搜索”按钮时如何关闭键盘?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7855361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dismiss keyboard when the UISearch Bar 'Search" button is pressed?
提问by cgossain
I've implemented a UISearch bar with the searching functionality set up, however when I press the "Search" button on the keyboard that shows up nothing happens. How can I get the keyboard to hide when the "Search" button is pressed while keeping the text in the search bar intact (To keep the search results present)?
我已经实现了一个设置了搜索功能的 UISearch 栏,但是当我按下键盘上的“搜索”按钮时,没有任何反应。如何在按下“搜索”按钮时隐藏键盘,同时保持搜索栏中的文本完好无损(以保持搜索结果存在)?
回答by rob mayoff
From Text, Web and Editing Programming Guide for iOS:
To dismiss the keyboard, you call the resignFirstResponder method of the text-based view that is currently the first responder.
要关闭键盘,请调用当前是第一响应者的基于文本的视图的 resignFirstResponder 方法。
So you should do this in your UISearchBarDelegate
:
所以你应该在你的UISearchBarDelegate
:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
// Do the search...
}
回答by ninahadi
Swift 4
Make sure you have UISearchBarDelegate defined in your UIViewController
Swift 4
确保在 UIViewController 中定义了 UISearchBarDelegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}