0

我希望能够将搜索功能添加到我的表格视图中。该表列出了各种商店位置。我希望用户能够按城市过滤。我一直在考虑以某种方式添加一个下拉列表,也许在 tableviewcell 中创建过滤器。有没有人这样做可以帮助我?

我已经在表格视图中有一个搜索栏控件,但它只搜索记录的一个字段。如何决定或选择搜索栏在我的数据中实际查找的字段?这是我的代码:

#pragma mark Content Filtering

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {

    // Update the filtered array based on the search text and scope.

    // Remove all objects from the filtered search array

    [self.filteredResultsArray removeAllObjects];

    // Filter the array using NSPredicate

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];

    [self.filteredResultsArray = [NSMutableArray arrayWithArray:[self.dates filteredArrayUsingPredicate:predicate]] retain];

}



#pragma mark - UISearchDisplayController Delegate Methods

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

    // Tells the table data source to reload when text changes

    [self filterContentForSearchText:searchString scope:

     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];

    // Return YES to cause the search result table view to be reloaded.

    return YES;

}



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

    // Tells the table data source to reload when scope bar selection changes

    [self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:

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

    // Return YES to cause the search result table view to be reloaded.

    return YES;

}

我的 self.dates 数组填充如下:

- (void)loadRecordsFromCoreData {

    [self.managedObjectContext performBlockAndWait:^{

        [self.managedObjectContext reset];

        NSError *error = nil;

        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:self.entityName];

        [request setSortDescriptors:[NSArray arrayWithObject:

                                     [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]]];

        self.dates = [self.managedObjectContext executeFetchRequest:request error:&error];



    }];

}

它与 initWithEntityName 是否有关系...

4

1 回答 1

0

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];

该谓词确定在您的数据中搜索哪个字段 - 在本例中为名称字段。如果您想搜索不同的字段,只需将 SELF.name 更改为 SELF.city 或其他字段。如果您想搜索多个字段或在过滤器中使用其他逻辑,请查看Apple 的 NSPredicate 编程指南

于 2013-01-19T17:14:23.773 回答