以编程方式创建可从多个视图使用的UISearchBar

时间:2013-06-04 11:22:13

标签: ios objective-c

我想创建一个可以在我的应用中从多个视图中查看和使用的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上初始化并显示正常时,搜索机制不起作用。我可以在搜索文本框中写入但不能执行任何操作。即使键盘上的“搜索”按钮也无效。

2 个答案:

答案 0 :(得分:0)

您必须根据您的使用方式在各自的控制器类中实现UISearchBarDelegate方法。

参考此

Documentation UISearchBarDelegate

扩展答案:

在“我的第一个视图.m”文件中,您需要实现UISearchBarDelegate方法以获取您的操作。

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{   
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //This is where your search button action fires. You can implement what you want to do after search button click in here.   
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
   //This fires whenever you change text in your search bar. For an example if you want to show search suggestions when a new letter is typed you can implement that in here.
}

您可以根据自己的要求使用其他委托方法。

答案 1 :(得分:-1)

在XIB中使用搜索栏和搜索显示控制器对象。只需将此对象拖放到XIB

即可

并实现表视图委托和数据源方法。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == self.aTableView)
    return [self.categories count];//normal table view
    return [self.searchCategories count];//search display controllers TableView
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"reusableCells";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:identifier] autorelease];
    NSString *text = nil;
    if(tableView == self.aTableView)
        text = [self.categories objectAtIndex:indexPath.row];
    else
       text = [self.searchCategories objectAtIndex:indexPath.row];

    cell.textLabel.text = text;

    return cell;
}

搜索显示控制器方法

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    if(self.searchCategories == nil){
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        self.searchCategories = arr;
        [arr release];
    }else{
        [self.searchCategories removeAllObjects];
    }

    for (NSString *aStr in self.categories) {
        if([[aStr lowercaseString] rangeOfString:[searchString lowercaseString]].location != NSNotFound){
           [self.searchCategories addObject:aStr];
        }
    }
    [controller.searchResultsTableView reloadData];
    return NO;
}



- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
    [self.aTableView setHidden:YES];
}
- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller{
    [self.aTableView setHidden:NO];
}

希望这会对你有所帮助。如果你有任何问题我建议你阅读

的详细信息
UISearchDisplayController