Подтвердить что ты не робот

Как использовать UISearchBar и UISearchDisplayController

У меня есть приложение, которое отображает довольно много данных в UITableView. Я уже добавил UISearchBar и UISearchDisplayController в Interface Builder к UITableView. Но я не знаю, как его использовать. Если бы кто-то мог быстро решить это, я был бы благодарен. Я просто требую, чтобы он работал по типу, чтобы найти совпадения поискового запроса в ячейках 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;  
}
4b9b3361

Ответ 1

  • Сначала добавьте UISearchDisplayController в представление таблицы
  • Затем установите его делегат.
  • Выполните следующие методы.

Демо-проект

В вашем файле .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];
}