我想创建一个 UISearchBar,可以从我的应用程序的多个视图中查看和使用。
出于这个原因,我在我的 AppDelegate 类中声明了一个 UISearchBar 属性,并在我的第一个 UIViewController 中对其进行了初始化。
@interface AppDelegate : UIResponder <UIApplicationDelegate>{
IBOutlet UIWindow *window;
}
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
我的第一个视图.h
@interface MainTableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>{
AppDelegate *appDelegate;
NSArray *searchResults;
}
@property (strong, nonatomic) IBOutlet UIBarButtonItem *accountPage;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *search;
我的第一个视图.m
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.search = [self.search initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(showSearchBar:)];
}
- (IBAction)showSearchBar:(id)sender{
UIBarButtonItem *searchItem = (UIBarButtonItem *) sender;
if (searchItem.tag == 0) {
if (!appDelegate.searchBar) {
appDelegate.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0,320,44)];
[[UISearchDisplayController alloc] initWithSearchBar:appDelegate.searchBar contentsController:self];
self.searchDisplayController.searchResultsDelegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.delegate = self;
[self.view addSubview:appDelegate.searchBar];
} else{
[appDelegate.searchBar setHidden:NO];
}
searchItem.tag = 1;
} else{
searchItem.tag = 0;
[appDelegate.searchBar setHidden:YES];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
}
// Set up the cell
return cell;
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSLog(@"filterContentForSearchText");
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@"(name contains[cd] %@)",
searchText];
searchResults = [appDelegate.elements filteredArrayUsingPredicate:resultPredicate];
}
- (BOOL) searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[self filterContentForSearchText:searchString
scope:[[appDelegate.searchBar scopeButtonTitles]
objectAtIndex:[appDelegate.searchBar
selectedScopeButtonIndex]]];
return YES;
}
但是,虽然搜索栏在 VC 上初始化并显示正常,但搜索机制却无法正常工作。我可以在搜索文本框中写字,但没有任何动作。甚至键盘上的“搜索”按钮也不起作用。