UISearchBar + didSelectRowAtIndexPath + cellForRowAtIndexPath

时间:2014-01-15 10:45:52

标签: iphone objective-c uitableview uisearchbar uisearchdisplaycontroller

我有以下UITableViewController + UISearchBar设置

@interface FeedTableView : UITableViewController <UISearchBarDelegate,UISearchDisplayDelegate>
{
    NSMutableArray *ArrayDatiOriginali;
    NSMutableArray *searchData;

    UISearchBar *searchBar;
    UISearchDisplayController *searchDisplayController;    
}

在加载方法

下面
- (void)viewDidLoad
{
    [super viewDidLoad];

    searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    searchDisplayController.delegate = self;
    searchDisplayController.searchResultsDataSource = self;
    searchDisplayController.searchResultsDelegate=self;

    self.tableView.tableHeaderView = searchBar;  tableView.
}

要在出现UISeach时选择数据/行,请使用

if(tableView==self.searchDisplayController.searchResultsTableView)
{
    NSLog(@"Riga corrente: %i",indexPath.row);
    appo=[searchData objectAtIndex:indexPath.row];
}

并且可以过滤表视图。

但是如果:

  • 搜索视图处于活动状态(显示已过滤的结果)
  • 我点击过滤结果的一行

然后

  • didSelectRowAtIndexPath被解雇,但
  • cellForRowAtIndexPath方法中的表达式

    if(tableView == self.searchDisplayController.searchResultsTableView)返回FALSE

如果UISearchView处于有效状态

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

制作两个阵列。

dataArray&amp; filteredDataArray &安培;将BOOL设为已过滤。

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
    isFiltered = FALSE;
}
else
{
    isFiltered = true;
}
[self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
isFiltered = FALSE;
[searchBar resignFirstResponder];
[self.tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(isFiltered)
{
    <#YOUR_MODEL#>= [filteredDataArray objectAtIndex:indexPath.row];
}
else
{
    <#YOUR_MODEL#>= [dataArray objectAtIndex:indexPath.row];
}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount;
if(isFiltered)
    rowCount = [filteredDataArray count];
else
    rowCount = [dataArray count];
return rowCount;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// [tableView deselectRowAtIndexPath:indexPath animated:YES];
if(isFiltered)
{
    <#YOUR_MODEL#>= [filteredDataArray objectAtIndex:indexPath.row];
}
else
{
    <#YOUR_MODEL#>= [dataArray objectAtIndex:indexPath.row];
}
//Pass it to any class or do what ever.
}

答案 1 :(得分:0)

要添加到上一个答案,您还需要添加:

searchBar.delegate = self;

然后,searchBar可以调用

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text