UISearchDisplayController は非常に便利で、検索の実装は非常に簡単です。
ただし、アプリで検索文字列が空でスコープボタンが選択されている検索結果を表示したい場合、問題が発生します。
検索結果テーブルを初期化して表示するには、何らかの検索文字列を入力する必要があるようです。
ユーザーがスコープを選択した直後に検索結果を表示する方法はありますか? まだ検索語を入力していませんか?
ありがとうビル
UISearchDisplayController は非常に便利で、検索の実装は非常に簡単です。
ただし、アプリで検索文字列が空でスコープボタンが選択されている検索結果を表示したい場合、問題が発生します。
検索結果テーブルを初期化して表示するには、何らかの検索文字列を入力する必要があるようです。
ユーザーがスコープを選択した直後に検索結果を表示する方法はありますか? まだ検索語を入力していませんか?
ありがとうビル
新しいスコープ ボタンをタップすると、selectedScopeButtonIndex が起動します。
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption;
次を使用して、ここで検索からタイトルの火をキャプチャできます。
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]
最初のスコープ インデックスでは機能しませんが、最後に使用された selectedScopeButtonIndex に基づいて最初に検索を開始することができます
スコープ ボタンを使用する回避策を次に示します。主なことは、検索結果を自動的に表示するスコープに余分な文字を追加することですが、これを行いたくないスコープについては必ず削除してください。
実装する必要があり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{
}