1

我的 有问题UISearchDisplayController,搜索无法正常工作。

这是我的代码:

    - (void)filterContentForSearchText:(NSString*)searchText 
                             scope:(NSString*)scope
{
    [self.searchResults removeAllObjects];

    for (int i = 0; i < [temp_category count]; i++) {
        BOOL foundResult = FALSE;

        if ([[temp_category objectAtIndex:i] rangeOfString:searchText].location != NSNotFound) {
            foundResult = TRUE;
        }
        if ([[price_producttitle objectAtIndex:i] rangeOfString:searchText].location != NSNotFound) {
            foundResult = TRUE;
        }
        if ([[price_type objectAtIndex:i] rangeOfString:searchText].location != NSNotFound) {
            foundResult = TRUE;
        }
        if ([[price_description objectAtIndex:i] rangeOfString:searchText].location != NSNotFound) {
            foundResult = TRUE;
        }
        if (foundResult) {

            NSNumber *result = [NSNumber numberWithInt:i];
            if ([self searchResults] == nil) {
                NSMutableArray *array = [[NSMutableArray alloc] init];
                [self setSearchResults:array];
                [array release];
            }

                [searchResults addObject:result];

        }
    }

    NSLog (@"array = %i", [searchResults count]);
    NSLog(@"%@",searchResults);
}

    -(BOOL)searchDisplayController:(UISearchDisplayController *)controller 
shouldReloadTableForSearchString:(NSString *)searchString
{

    [self filterContentForSearchText:searchString 
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]]; 

    return YES;

}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller 
shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] 
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:searchOption]]; 

    return YES;
}

但我仍然感到困惑,因为当我从第一个字母开始搜索时,它会给出正确的命中。但是当我输入第二个字母时,它只显示一个结果(据我从数据样本中了解到的还有更多)。我做错了什么。我认为这与用户输入文本时有关,但我很困惑我应该使用哪种方法。

我现在拥有的代码是: 教程和 这个SO 问题的组合。

有人可以给我一个好的方向提示吗?显示结果很好,只有这方面困扰我。我认为这与触发方法和[self.searchResults removeAllObjects];.

4

1 回答 1

1

我想添加我的代码,但问题是我仍然使用上面的代码,但我手动实现 UISearchBar(我在教程的其他地方找到)而不是使用 SearchDisplayController。我在使用 SearchDisplayController 时导航栏消失时也遇到了困难,这给了我足够的理由自己实现它而不是使用 SearchDisplayController。它给你更多的自由。

起初看起来工作量很大,所以我选择使用 SearchDisplayController,但我真的建议任何需要修改或想要更多自由的人,请使用 UISearchBar 和 UITableView 手动进行 :)

于 2012-07-08T17:43:57.617 回答