当UISearchDisplayController处于非活动状态时,保持搜索项可见

时间:2011-01-21 04:35:07

标签: iphone cocoa-touch uisearchbar 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";

更好的建议仍然受到欢迎!

2 个答案:

答案 0 :(得分:8)

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

如果用户单击搜索按钮并且您想要隐藏searchController接口,则必须确定要在搜索中放置的文本(例如,在列表中选择最佳匹配结果)。

此示例只是让用户点击搜索按钮时搜索词保持可见且不变:

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

希望这有帮助, 文森特

答案 1 :(得分:4)

手动重置搜索栏中的字符串会再次触发一些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!
}
相关问题