UISearchDisplayController - 如何仅选择范围按钮但显示空搜索字符串来显示搜索结果

时间:2010-04-26 04:54:35

标签: iphone uisearchdisplaycontroller

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

然而,当我在我的应用程序中,我希望显示搜索结果为空搜索字符串但选择范围按钮时,我遇到了问题。

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

有没有办法在用户选择范围但尚未输入搜索词后立即显示搜索结果?

由于 比尔

3 个答案:

答案 0 :(得分:2)

当您点按新范围按钮时,selectedScopeButtonIndex会触发:

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

您可以使用以下方式从搜索中捕获标题:

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分: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{
}