我的应用使用 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";
仍然欢迎更好的建议!
最佳答案
实际上,您不能在 searchBarSearchButtonClicked 方法中使用相同的代码,因为您没有 indexPath 来选择 searchMatches 数组中的正确元素。
如果用户单击搜索按钮并且您想要隐藏 searchController 界面,您必须弄清楚要在搜索中放入哪些文本(例如在列表中选择最佳匹配结果)。
此示例只是让搜索词在用户单击搜索按钮时保持可见且不变:
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSString *str = searchBar.text;
[self.searchController setActive:NO animated:YES];
self.searchController.searchBar.text = str;
}
希望这有帮助, 文森特
关于iphone - 当 UISearchDisplayController 处于非事件状态时保持搜索词可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4755411/