5

我的应用使用UISearchDisplayController。当用户输入搜索词时,我希望它在搜索栏中保持可见。如果用户选择了其中一个匹配的结果,那么这将起作用,但如果用户单击“搜索”按钮则不起作用。当UISearchDisplayController处于非活动状态时,保持搜索字词可见

这工作:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     NSString *selectedMatch = [self.searchMatches objectAtIndex:indexPath.row]; 
     [self.searchDisplayController setActive:NO animated:YES]; 
     [self.searchDisplayController.searchBar setText:selectedMatch]; 

     return; 
    } 
    ... 

但是,如果我做同样的事情在-searchBarSearchButtonClicked:文本不会保留在搜索栏。关于在这种情况下如何完成此任何想法?

相关的,如果我设置了搜索栏的文本(但是保持UISearchDisplayController不活动),这会触发searchResultsTableView的显示。我只想显示当用户点击搜索栏时。

编辑:找到一个解决办法来设置搜索栏的文本不显示在任何时候searchResultsTableView:

// This hacky YES NO is to keep results table view hidden (animation required) when setting search bar text 
[self.searchDisplayController setActive:YES animated:YES]; 
[self.searchDisplayController setActive:NO animated:YES]; 
self.searchDisplayController.searchBar.text = @"text to show"; 

更好的建议,欢迎仍然!

回答

7

实际上,您不能在searchBarSearchButtonClicked方法中使用相同的代码,因为您没有indexPath可以在您的searchMatches数组中选择正确的元素。

如果用户单击搜索按钮并且想要隐藏searchController界面,则必须找出要在搜索中放置哪些文本(例如,在列表中选择最佳匹配结果)。

这个例子只是让搜索项保持可见和不变的,当用户点击搜索按钮:

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar { 
    NSString *str = searchBar.text; 
    [self.searchController setActive:NO animated:YES]; 
    self.searchController.searchBar.text = str; 
} 

希望这有助于 文森特

+0

啊谢谢!我在做`[self.searchController setActive:NO animated:YES]; self.searchController.searchBar.text = searchBar.text;`但显然`searchBar.text`不再是我认为这是由于`setActive`方法清空搜索栏。 – 2011-01-21 07:25:01

3

重置手动在搜索栏的字符串触发一些的UISearchDisplayDelegate方法。在这种情况下,这可能不是你想要的。

我将修改vdaubry回答了一下,它给了我:

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar { 
    NSString *str = searchBar.text; 
    [self.searchController setActive:NO animated:YES]; 
    self.searchController.delegate = nil; 
    self.searchController.searchBar.text = str; 
    self.searchController.delegate = self //or put your delegate here if it's not self! 
} 
相关问题