2010-04-26 47 views
9

UISearchDisplayController非常方便,實現搜索非常簡單。UISearchDisplayController - 如何僅通過範圍按鈕顯示搜索結果但選擇空搜索字符串

但是,當我在我的應用程序中,我想顯示空搜索字符串的搜索結果,但選擇範圍按鈕時,碰到問題。

它似乎是必須輸入一些搜索字符串,以獲得搜索結果表被初始化和顯示。

有沒有什麼方法可以在用戶選擇範圍後立即顯示搜索結果,但是沒有輸入搜索詞呢?

感謝 比爾

+0

我有同樣的問題。有人有答案嗎? – 2011-04-27 20:20:54

回答

2

當你點擊一個新的作用域按鈕selectedScopeButtonIndex火災:

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption; 

你可以捕捉標題火災在這裏下車搜索使用:

[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption] 

榮獲」 t在初始範圍索引上工作,但是您可以根據最後使用的selectedScopeButtonIndex開始初始化搜索

1

我是在同樣的事情之後,剛剛在蘋果開發者論壇中發現了一些東西:UISearchDisplayController的實現方式是在輸入一些文本之前不會顯示結果表。還有一個關於這方面的錯誤報告:ID#8839635.

我通過在搜索欄下面放置一個分段控件,模仿範圍欄來解決它。

0

以下是使用範圍按鈕的解決方法。主要是爲要自動顯示搜索結果的作用域添加一個額外字符,但請確保將其刪除了不想執行此操作的作用域。

您需要實現searchBar:textDidChange以及searchBar:selectedScopeButtonIndexDidChange:

// scope All doesn't do a search until you type something in, so don't show the search table view 
// scope Faves and Recent will do a search by default 
#define kSearchScopeAll 0 
#define kSearchScopeFaves 1 
#define kSearchScopeRecent 2 

// this gets fired both from user interaction and from programmatically changing the text 
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 
    [self initiateSearch]; 
} 


- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{ 
    NSString *searchText = self.searchDisplayController.searchBar.text; 
    // if we got here by selecting scope all after one of the others with no user input, there will be a space in the search text 

    NSString *strippedText = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
    if ((selectedScope == kSearchScopeAll) && (strippedText.length == 0) && (searchText.length != 0)){ 
     self.searchDisplayController.searchBar.text = @""; 
    } else { 
     [self initiateSearch]; 
    } 
} 

-(void)initiateSearch{ 
    NSString *searchText = self.searchDisplayController.searchBar.text; 
    NSInteger scope = self.searchDisplayController.searchBar.selectedScopeButtonIndex; 
    if ((searchText.length == 0) && (scope != kSearchScopeAll)){ 
     self.searchDisplayController.searchBar.text = @" "; 
    } 
    switch (scope) { 
     case kSearchScopeAll: 
      [self searchAll:searchText]; 
      break; 
     case kSearchScopeFaves: 
      [self searchFavorites:searchText]; 
      break; 
     case kSearchScopeRecent: 
      [self searchRecents:searchText]; 
      break; 

     default: 
      break; 
    } 
} 

// assume these trim whitespace from the search term 
-(void)searchAll:(NSString *)searchText{ 
} 

-(void)searchFavorites:(NSString *)searchText{ 
} 

-(void)searchRecents:(NSString *)searchText{ 
}