我有一个行为正常的UISearchBar - 如果我点击“搜索”或“取消”,键盘会消失。
但是,当我在导航堆栈上推送新的视图控制器时,如果键盘打开,它将不会关闭。它保留在旧视图控制器中,如果我导航回它,键盘仍会显示。
我很难过,因为我的searchBarShouldEndEditing方法是按预期调用的,我做[activeSearchBar resignFirstResponder]。这适用于“搜索”或“取消”,但不适用于视图消失的情况。
我的委托代码:
#pragma mark Search bar delegate methods__________________________
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)activeSearchBar
{
NSLog(@"searchBarShouldBeginEditing");
[activeSearchBar setShowsCancelButton:TRUE animated:YES];
if (!showSearchType)
return TRUE;
if([UIView respondsToSelector:@selector(animateWithDuration:animations:)]) {
// iOS 4.0 and later
[UIView animateWithDuration:0.3 animations:^ {
searchTypeView.frame = CGRectMake(0, 44, 320, 69);
searchTypeView.bounds = CGRectMake(0, 0, 320, 69);
grayBg.alpha = 0.6;
}];
} else {
// Before iOS 4.0
searchTypeView.frame = CGRectMake(0, 44, 320, 69);
searchTypeView.bounds = CGRectMake(0, 0, 320, 69);
grayBg.alpha = 0.6;
}
self.frame = CGRectMake(0, 0, 320, 113);
[self bringSubviewToFront:searchTypeView];
[self bringSubviewToFront:activeSearchBar];
return TRUE;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)activeSearchBar
{
NSLog(@"searchBarShouldEndEditing");
if ([activeSearchBar isFirstResponder]) {
NSLog(@"activeSearchBar isFirstResponder");
}
[activeSearchBar resignFirstResponder];
[activeSearchBar setShowsCancelButton:FALSE animated:YES];
if (!showSearchType)
return TRUE;
if([UIView respondsToSelector:@selector(animateWithDuration:animations:)]) {
// iOS 4.0 and later
[UIView animateWithDuration:0.3 animations:^ {
searchTypeView.frame = CGRectMake(0, 9, 320, 69);
searchTypeView.bounds = CGRectMake(0, 0, 320, 0);
grayBg.alpha = 0;
}];
} else {
// Before iOS 4.0
searchTypeView.frame = CGRectMake(0, 9, 320, 69);
searchTypeView.bounds = CGRectMake(0, 0, 320, 0);
grayBg.alpha = 0;
}
self.frame = CGRectMake(0, 0, 320, 44);
return TRUE;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)activeSearchBar {
NSLog(@"searchBarTextDidEndEditing");
if ([activeSearchBar isFirstResponder]) {
NSLog(@"activeSearchBar isFirstResponder");
}
[activeSearchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)activeSearchBar
{
NSLog(@"searchBarCancelButtonClicked");
[activeSearchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)activeSearchBar
{
NSLog(@"searchBarSearchButtonClicked");
self.query = searchBar.text;
[activeSearchBar resignFirstResponder];
[searchView startSearch];
}
输出:
2011-12-07 20:00:33.061 MyApp[55725:307] searchBarShouldEndEditing
2011-12-07 20:00:33.063 MyApp[55725:307] activeSearchBar isFirstResponder
2011-12-07 20:00:33.066 MyApp[55725:307] searchBarTextDidEndEditing
感谢您的任何想法!
答案 0 :(得分:6)
你也可以:在.h文件中声明searchBar变量,make属性等...然后在你的按钮点击事件方法上,推送另一个视图,写第一行:
[yourSearchBar resignFirstResponder];
答案 1 :(得分:2)
好的,我找到了一个解决方案,虽然它不是很好。
在父视图控制器中,我将以下行放在会触发新视图控制器推送到导航堆栈的任何内容之前:
[self.view endEditing:YES];
这似乎有点脆弱且容易出错......我很想知道是否有更好的方法。