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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:00:04  来源:igfitidea点击:

How to dismiss keyboard when the UISearch Bar 'Search" button is pressed?

objective-ciosuisearchbar

提问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:

来自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()
}