xcode 使用 UISearchBar 搜索表格视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14860620/
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-09-15 02:45:53  来源:igfitidea点击:

Searching a table view with UISearchBar

iosxcode

提问by user2014474

I am using this code to search through a UItableView:

我正在使用此代码来搜索 UItableView:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {



if(searchText.length == 0)
{
    isFiltered = FALSE;
}
else
{
    isFiltered = TRUE;


    if (filteredTableData == nil)
       filteredTableData = [[NSMutableArray alloc] init];
    else 
        [filteredTableData removeAllObjects];

    for (NSString* string in self.itemArray)
    {
        NSRange nameRange = [string rangeOfString:searchBar.text options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
        if(nameRange.location != NSNotFound)
        {
            [filteredTableData addObject:string];
        }
    }
}
[tableView reloadData]; 
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}

Everything works fine, but if I press the cancel button which appears when I start editing, my list doesn't come back, but the search results remain. To show back the list, I have to begin typing, even a single character in the searchbar and then delete it or press the "x" to see all the list. Is there a way to block the cancel button? Or to show the list when it is pressed?

一切正常,但如果我按下开始编辑时出现的取消按钮,我的列表不会返回,但搜索结果仍然存在。为了显示列表,我必须开始输入,即使是搜索栏中的单个字符,然后将其删除或按“x”以查看所有列表。有没有办法阻止取消按钮?或者在按下时显示列表?

回答by Rahul Wakade

Implement - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar delegate method of UISearchBar. In that add all objects(initial objects in table) in filteredTableData array and reload table.

实现 - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar UISearchBar 的委托方法。在其中添加filteredTableData数组中的所有对象(表中的初始对象)并重新加载表。

   -(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
    {       
        [filteredTableData removeAllObjects];
        [filteredTableData addObjectsFromArray:self.itemArray];
        [tableView reloadData];
    }

Also you don't need to maintain flag isFiltered if you are using it for choosing data source array for reloading table(in table view data source methods). e.g.

如果您使用它来选择数据源数组以重新加载表(在表视图数据源方法中),则您也不需要维护标志 isFiltered。例如

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   if(isFiltered) 
      return filteredTableData.count 
   else
      return self.itemArray.count
}

If you maintain data in filteredTableData array all time, you don't need to do this. Your method will look like-

如果您一直在filteredTableData 数组中维护数据,则无需执行此操作。你的方法看起来像-

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
      return filteredTableData.count 
}

Initially in init or viewDidLoad method of controller add all objects in filteredTableData and use only this array for reloading table.

最初在控制器的 init 或 viewDidLoad 方法中,添加filteredTableData 中的所有对象,并仅使用此数组来重新加载表。

Hence your method will look like-

因此你的方法看起来像 -

 -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
 {
     if(searchText.length == 0)
     {
         [filteredTableData removeAllObjects];
         [filteredTableData addObjectsFromArray:self.itemArray];
     }
     else
     {
        [filteredTableData removeAllObjects];

        for (NSString* string in self.itemArray)
        {
            NSRange nameRange = [string rangeOfString:searchBar.text options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
            if(nameRange.location != NSNotFound)
            {
                [filteredTableData addObject:string];
            }
        }
     }
     [tableView reloadData]; 
    }

回答by Bot

I don't use that method but use the following and it works perfectly

我不使用该方法,而是使用以下方法,它可以完美运行

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@",searchString];
    self.filteredCustomers = [[self.customers filteredArrayUsingPredicate:predicate] mutableCopy];

    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchDisplayController setActive:NO animated:NO];
    self.filteredCustomers = nil;
    [self.tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomerCell";
    NSDictionary *customerObject;

    CustomerListCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (self.searchDisplayController.active) {
        customerObject = [[NSDictionary alloc] initWithDictionary:[self.filteredCustomers objectAtIndex:indexPath.row]];
    } else {
        customerObject = [[NSDictionary alloc] initWithDictionary:[[self.customerData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
    }
    cell.textLabel.text = [customerObject objectForKey:@"name"];
    cell.customerName = [customerObject objectForKey:@"name"];
    cell.customerId = [customerObject objectForKey:@"customer_id"];

    return cell;
}