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

Joh*_*ool 6 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;
    }
    ...
Run Code Online (Sandbox Code Playgroud)

但是,如果我在-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";
Run Code Online (Sandbox Code Playgroud)

更好的建议仍然欢迎!

vda*_*bry 8

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

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

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

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

希望这有帮助,文森特