如何使用 UISearchBar 和 UISearchDisplayController?

26

我有一个应用程序,它在UITableView中显示了相当多的数据。我已经在Interface Builder中向UITableView添加了UISearchBarUISearchDisplayController,但是我不知道如何使用它。如果有人能够为此提供一个快速的解决方案,我将不胜感激。我只需要它能够在输入时在UITableView单元格(或从数组中)中查找搜索查询的匹配项。

更新1:这里是numberOfRowsInSection方法的代码:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
{  
if (isSearching) {  
        return [searchResults count];  
    }  
    else {  
        if (section == 0) {  
            return 1;  
        }  
        else if (section == 1) {  
            return [basicQuantities count];  
        }  
        else if (section == 2) {  
            return [physicalQuantities count];  
        }  
    }  

    return nil;  
}

你尝试过任何代码吗?你在那段代码中遇到了什么问题? - Amar
1
未来的开发者请注意:UISearchDisplayController在iOS 8中已被弃用,请使用UISearchController代替。 - Blaszard
2个回答

84
  • 首先将UISearchDisplayController添加到您的表视图中
  • 然后设置其委托对象。
  • 实现以下方法。

Demo 项目

在您的 .h 文件中

    @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {

    NSMutableArray *contentList;
    NSMutableArray *filteredContentList;
    BOOL isSearching;
}
@property (strong, nonatomic) IBOutlet UITableView *tblContentList;
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *searchBarController;

在您的.m文件中

填充示例数据(仅为演示目的而选填)

- (void)viewDidLoad {
    [super viewDidLoad];
    contentList = [[NSMutableArray alloc] initWithObjects:@"iPhone", @"iPod", @"iPod touch", @"iMac", @"Mac Pro", @"iBook",@"MacBook", @"MacBook Pro", @"PowerBook", nil];
    filteredContentList = [[NSMutableArray alloc] init];
}

现在实现表视图的代理和数据源

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (isSearching) {
        return [filteredContentList count];
    }
    else {
        return [contentList 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];
    }

    // Configure the cell...
    if (isSearching) {
        cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
    }
    else {
        cell.textLabel.text = [contentList objectAtIndex:indexPath.row];
    }
    return cell;

}

搜索功能用于搜索

- (void)searchTableList {
    NSString *searchString = searchBar.text;

    for (NSString *tempStr in contentList) {
        NSComparisonResult result = [tempStr compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
        if (result == NSOrderedSame) {
            [filteredContentList addObject:tempStr];
        }
    }
}

搜索栏实现

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    isSearching = YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSLog(@"Text change - %d",isSearching);

    //Remove all objects first.
    [filteredContentList removeAllObjects];

    if([searchText length] != 0) {
        isSearching = YES;
        [self searchTableList];
    }
    else {
        isSearching = NO;
    }
    // [self.tblContentList reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"Cancel clicked");
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"Search Clicked");
    [self searchTableList];
}

实际上我还在尝试实现这个功能。在numberOfRowsInSection方法中出现了异常。 - Youssef Moawad
1
是的,一旦我点击UISearchBar,异常就会被发送。 - Youssef Moawad
1
@icodebuster,感谢您提供的示例。我想提醒您一个错误,您应该实现searchBarTextDidEndEditing并将isSearching设置为NO。否则,在向下滚动时,在cellForRowAtIndexPath中从错误的数组加载数据会导致异常。 - Ömer Faruk Almalı
7
不是使用 if(isSearching) 检查,而是检查传入的表视图是否等于 UISearchDisplayController,我认为这是一个更安全的检查方式。if(self.searchController.searchResultsTableView == tableView) - SirRupertIII
2
@icodebuster,UISearchDisplayController在iOS9中已经被弃用,请使用新的搜索方式更新您的演示代码。 - ChenSmile
显示剩余17条评论

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接