我有一个顶部带有搜索栏的表格视图。当我点击搜索时,它会被呼叫到第一响应者并出现键盘。搜索栏有一个取消按钮,但是当表格为空时,我希望用户能够点击空表格行上的任意位置以将搜索栏和键盘作为第一响应者。我该怎么做呢?
2 回答
您必须创建自己的 UITableView 类来覆盖 touchesEnded 方法。然后你可以回调你的委托,它应该是你的视图控制器,并告诉它告诉你的 UISearchBar 辞职第一响应者。
UITableView 派生类看起来像这样:
#import <UIKit/UIKit.h>
@interface FRTableView : UITableView {
}
@end
// ------------------------------
#import "FRTableView.h"
@implementation FRTableView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
NSLog(@"Touches ended");
// Bubble back up to your view controller which should be this
// table view's delegate.
if ([self delegate] && [[self delegate] respondsToSelector:@selector(touchEnded)])
[[self delegate] performSelector:@selector(touchEnded)];
}
@end
确保在 Interface Builder 中设置表格视图以使用自定义类而不是普通的 UITableView 类。然后在您的视图控制器中,实现我称为 touchEnded 的选择器,如下所示:
- (void)touchEnded;
{
NSLog(@"Back in root view controller.");
[searchBar resignFirstResponder];
}
其中 searchBar 是一个连接到 Interface Builder 中的 UISearchBar 的 IBOutlet。
你不要尝试...... UISearchDisplayController
只需在你的 .h 文件中定义这些
IBOutlet UISearchBar* mySearchBar; UISearchDisplayController* mySearchDisplayController; IBOutlet UITableView* myTableView;
并在 .h 中处理 UISearchBarDelegate
现在在 .m 文件中只写这些代码
mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self]; mySearchDisplayController.searchResultsDelegate = self; mySearchDisplayController.searchResultsDataSource = self; mySearchDisplayController.delegate = self;
我希望这可能会有所帮助.......