2010-12-04 32 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,但結果表不會重新加載。

如果存在以前的搜索字符串,則轉換有點粗糙。如果我發現更好的實現沒有大致的過渡,我會更新我的答案。