Hide the keybord on clicking enter button or search button
I've added the UISearchBar
button inside the UIBarButtonItem
inside the toolbar button.
In the below form:
// search bar
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 260, 44)];
UIBarButtonItem *searchBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
[search开发者_如何转开发Bar release];
[buttons addObject:searchBarButtonItem];
Now the problem in when I click on the UISearchBar
keyboard appears. I'd like to hide the keyboard on clicking in enter or search button. How can i do this?
Implement a method from UISearchBarDelegate
:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
}
For Swift
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
You need to process the UISearchBarDelegate
protocol methods.
In the following methods, call -resignFirstResponder
method of UISearchBar.
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
The detail of above delegate methods can be found in the Apple official document. I often resign first responder inside those delegate methods as the end of searching.
you can use UISEarchBar's delegate method
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
and for enter (not tested)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText; // called when text changes (including clear)
{
if ([searchText isEqualToString:@"\n"])
[searchBar resignFirstResponder];
}
Hope this helps you...
In the header file, add or connect to the UISearchBar outlet: should look something like this:
@property (weak, nonatomic) IBOutlet UISearchBar *searchBarName;
Then, in the implementor, add the following:
self.searchBarName.delegate = self;
in the viewDidLoad
function.
Then add the following function:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.searchBarName resignFirstResponder];
}
Also as mentioned above ensure that this is added/extended in the header
UISearchBarDelegate
use [textField endEditing:YES];
, it should work for you, or you can create an oject of ur button and do [self.buttonObj resignFirstResponder]
精彩评论