我想实现这个
1)当用户开始在文本字段中输入时,popOver会闪烁并按照文本字段中输入的字符串显示弹出窗口中表格视图中的项目列表。
2)此外,每输入一个新字母都应该刷新这些数据。
一种预测性搜索。
请帮助我,并提出可行的方法来实现这一点。
答案 0 :(得分:7)
UISearchDisplayController为你做了大部分繁重的工作。
在视图中放置一个UISearchBar(不是UITextField),并将UISearchDisplayController连接到它。
// ProductViewController.h
@property IBOutlet UISearchBar *searchBar;
@property ProductSearchController *searchController;
// ProductViewController.m
- (void) viewDidLoad
{
[super viewDidLoad];
searchBar.placeholder = @"Search products";
searchBar.showsCancelButton = YES;
self.searchController = [[[ProductSearchController alloc]
initWithSearchBar:searchBar
contentsController:self] autorelease];
}
我通常是UISearchDisplayController的子类,并拥有它自己的委托,searchResultsDataSource和searchResultsDelegate。后两者以正常方式管理结果表。
// ProductSearchController.h
@interface ProductSearchController : UISearchDisplayController
<UISearchDisplayDelegate, UITableViewDelegate, UITableViewDataSource>
// ProductSearchController.m
- (id)initWithSearchBar:(UISearchBar *)searchBar
contentsController:(UIViewController *)viewController
{
self = [super initWithSearchBar:searchBar contentsController:viewController];
self.contents = [[NSMutableArray new] autorelease];
self.delegate = self;
self.searchResultsDataSource = self;
self.searchResultsDelegate = self;
return self;
}
搜索栏中的每个按键都会调用searchDisplayController:shouldReloadTableForSearchString:
。快速搜索可以在这里直接实现。
- (BOOL) searchDisplayController:(UISearchDisplayController*)controller
shouldReloadTableForSearchString:(NSString*)searchString
{
// perform search and update self.contents (on main thread)
return YES;
}
如果您的搜索可能需要一些时间,请在后台使用NSOperationQueue进行搜索。在我的示例中,ProductSearchOperation将在完成时调用showSearchResult:
。
// ProductSearchController.h
@property INSOperationQueue *searchQueue;
// ProductSearchController.m
- (BOOL) searchDisplayController:(UISearchDisplayController*)controller
shouldReloadTableForSearchString:(NSString*)searchString
{
if (!searchQueue) {
self.searchQueue = [[NSOperationQueue new] autorelease];
searchQueue.maxConcurrentOperationCount = 1;
}
[searchQueue cancelAllOperations];
NSInvocationOperation *op = [[[ProductSearchOperation alloc]
initWithController:self
searchTerm:searchString] autorelease];
[searchQueue addOperation:op];
return NO;
}
- (void) showSearchResult:(NSMutableArray*)result
{
self.contents = result;
[self.searchResultsTableView
performSelectorOnMainThread:@selector(reloadData)
withObject:nil waitUntilDone:NO];
}
答案 1 :(得分:1)
听起来你已经很好地了解了一个实现。我的建议是在顶部带有搜索栏的popover中显示UITableView,然后使用搜索词驱动表视图的数据源,并在每次用户输入框时在表视图上调用reloadData