ios 如何使用 UISearchBar 和 UISearchDisplayController

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18719517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:03:29  来源:igfitidea点击:

How do I use the UISearchBar and UISearchDisplayController

iosobjective-cuitableviewuisearchbaruisearchdisplaycontroller

提问by Youssef Moawad

I have an app which displays quite a lot of data in a UITableView. I already added the UISearchBarand UISearchDisplayControllerin Interface Builder to the UITableView. But I do not know how to use it. If someone could provide a quick solution to this, I would be grateful. I just require it to work as you type to find matches of the search query in the UITableViewcells (or from an array).

我有一个应用程序,它在UITableView. 我已经将Interface Builder 中的UISearchBar和添加UISearchDisplayControllerUITableView. 但我不知道如何使用它。如果有人可以为此提供快速解决方案,我将不胜感激。我只需要它在您键入以在UITableView单元格(或从数组中)中查找搜索查询的匹配项时工作。

UPDATE 1: Here's the code from thenumberOfRowsInSectionmethod:

更新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;  
}

回答by icodebuster

  • First add the UISearchDisplayControllerto your table view
  • Then set its delegate.
  • Implement the following methods.
  • 首先将UISearchDisplayController添加到您的表格视图中
  • 然后设置它的委托。
  • 实现以下方法。

Demo Project

演示项目

In your .h File

在您的 .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;

In your .m File

在您的 .m 文件中

Filling the sample data (Optional Only For Demo Purpose)

填充样本数据(可选仅用于演示目的)

- (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];
}

Now implement the Table View Delegate and Datasource

现在实现表视图委托和数据源

- (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;

}

Search Function Responsible For Searching

负责搜索的搜索功能

- (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];
        }
    }
}

Search Bar Implementation

搜索栏实现

- (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];
}

回答by Grzegorz Krukowski

Here is a good tutorial how to do that. It's too much to just write about it :)

这是一个很好的教程如何做到这一点。只是写它太多了:)

http://www.appcoda.com/how-to-add-search-bar-uitableview/

http://www.appcoda.com/how-to-add-search-bar-uitableview/