我想实现这个
1)当用户开始在文本字段中键入时,popOver会闪烁,并根据在textfield中输入的字符串显示弹出窗口中表格视图中的项目列表.
2)此外,每次输入的新字母都应刷新此数据.
一种预测性搜索.
请帮助我,并提出可行的方法来实现这一点.
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];
}
Run Code Online (Sandbox Code Playgroud)
我通常将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;
}
Run Code Online (Sandbox Code Playgroud)
搜索栏中的每个按键调用searchDisplayController:shouldReloadTableForSearchString:.快速搜索可以直接在这里实现.
- (BOOL) searchDisplayController:(UISearchDisplayController*)controller
shouldReloadTableForSearchString:(NSString*)searchString
{
// perform search and update self.contents (on main thread)
return YES;
}
Run Code Online (Sandbox Code Playgroud)
如果您的搜索可能需要一些时间,请在后台使用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];
}
Run Code Online (Sandbox Code Playgroud)