9

UISearchDisplayController 非常方便,实现搜索非常简单。

但是,当我想在我的应用程序中显示带有空搜索字符串但选择范围按钮的搜索结果时,我遇到了问题。

似乎必须输入一些搜索字符串才能初始化和显示搜索结果表。

用户选择范围但尚未输入搜索词后,有什么方法可以立即显示搜索结果?

谢谢比尔

4

3 回答 3

2

当您点击一个新的范围按钮时, selectedScopeButtonIndex 会触发:

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

您可以使用以下方法在此处捕获标题:

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

不适用于初始范围索引,但您可以根据上次使用的 selectedScopeButtonIndex 启动搜索

于 2011-05-01T11:00:50.567 回答
1

我也在追求同样的事情,只是在 Apple 开发者论坛中发现了一些东西:它UISearchDisplayController的实现方式是在输入一些文本之前不会显示结果表。还有一个关于此的错误报告:ID# 8839635。

我通过在搜索栏下方放置一个分段控件来解决它,模仿范围栏。

于 2011-07-05T22:54:57.033 回答
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{
}
于 2012-12-03T04:41:22.080 回答