2010-12-04 77 views
3

我有一个应用程序,它异步搜索远程API并使用iOS的UISearchDisplayController显示UI。以编程方式使用UISearchDisplayController

对于已保存的搜索功能,我一直试图以编程方式使用UISearchDisplayController,以便启动搜索,并将用户界面设置为回到以前的位置。 (即,我想调出搜索栏,并设置搜索条件。)

searchTableViewController.searchDisplayController.searchBar.text = mySearchTerm; 
//[...] 
[searchTableViewController.searchDisplayController setActive:YES animated:YES]; 
[searchTableViewController performSearch]; 

我已经试过到目前为止的代码,上面doesn't似乎做的伎俩。虽然它能够正确显示搜索栏,设置搜索词并执行搜索,但系统似乎无法将其视为有效的搜索。如果我在结果视图中使用手指使键盘消失,则搜索词会自行重置,结果将消失。

ex1 ex2

帮助表示赞赏。谢谢!

+0

http://stackoverflow.com/questions/8696260/creating-a-uisearchdisplaycontroller-programmatically – Hemang 2015-02-11 12:20:03

回答

0

我遇到了同样的问题。我通过创建ivar NSString * savedSearchString;并在UISearchDisplayController的委托中添加以下方法来解决此问题。

- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller 
{ 
    // saves search string for next search 
    [savedSearchString release]; 
    savedSearchString = [controller.searchBar.text retain]; 
    return; 
} 

- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller 
{ 
    // shows keyboard and gives text box in searchBar the focus 
    [controller.searchBar becomeFirstResponder]; 

    // shows previous search results 
    if ((savedSearchString)) 
     controller.searchBar.text = savedSearchString; 

    return; 
} 

添加行controller.searchBar.text = savedSearchString;searchDisplayControllerWillBeginSearch:将导致搜索词出现在的UISearchBar,但结果表不会重新加载。

如果存在以前的搜索字符串,则转换有点粗糙。如果我发现更好的实现没有大致的过渡,我会更新我的答案。