【问题标题】:How to use UISearchBar with tableView that has sections如何将 UISearchBar 与具有部分的 tableView 一起使用
【发布时间】:2011-08-17 07:54:52
【问题描述】:

好的,我正在努力在具有部分的 tableView 上实现 UISearchBar。这可能是错误的,但是为了第一次填充表格视图,我有一个包含很多条目的数组,然后填充如下所示的部分:

if(indexPath.section ==0){

            [cell.textLabel setText:[tableData objectAtIndex:indexPath.row]];                   
    }else if(indexPath.section ==1){

            [cell.textLabel setText:[tableData objectAtIndex:indexPath.row+4]];                     
    }else if(indexPath.section ==2){

            [cell.textLabel setText:[tableData objectAtIndex:indexPath.row+8]];                     
    }

这远非优雅,但它确实有效。现在我正在尝试连接 UISearchBar,这是我遇到问题的方法:

   - (void)searchBar:(UISearchBar *)sBar textDidChange:(NSString *)searchText
    {
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""] || searchText==nil){
    [tableView reloadData];
    return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSRange r = [name rangeOfString:searchText];
    if(r.location != NSNotFound)
    {

            [tableData addObject:name];

    }

    [pool release];
}

[tableView reloadData];
  }

因此,我再次创建了一个符合搜索条件的条目数组,但是当我尝试重新加载我的 tableView 时,它会因为期待部分而变得混乱。但我想要的只是一个普通的无节 tableView 中的结果。

如何使用带有部分的 tableView 实现这个 UISearchBar?

谢谢

【问题讨论】:

  • 为不同的部分保留不同的数组。

标签: iphone uitableview uisearchbar reload


【解决方案1】:

您不需要保留另一个变量;只需询问tableView 参数即可查看谁在询问节数。例如,假设您的数据在 fetchedResultsController 中可用:

   if (tableView == self.searchDisplayDisplayController.searchResultsTableView) {
      // your table is the search results table, so just return 1
      return 1;
   } else {
      // your table is your "own" table
      return [[self.fetchedResultsController sections] count];
   }

我在我的许多表视图委托和数据源方法中都做同样的事情。

【讨论】:

    【解决方案2】:

    在您输入搜索时设置一个 BOOL 并相应地调整您的节数

    例如

    在 viewDidLoad 中

     BOOL isSearching = NO;
    

    输入 textDidChange 方法时设置为 YES。

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        int t;
    if (isSearching) t = 1
    else {
    t=  array.count;
    }
    return t;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多