如何使用搜索控制器在UITableView中为SearchBar添加搜索图标部分

时间:2013-05-20 23:09:14

标签: ios nsarray uitableview uisearchdisplaycontroller

我正在尝试将搜索图像(放大镜)添加为部分,以便轻松转到搜索栏。

这是我遇到的问题: enter image description here

我设置部分的代码如下:

注意:self.fbFriends是一个字典数组,包含用户的facebook好友。

self.fbFriends = [[NSArray alloc] initWithArray:[[MESCache sharedCache] facebookFriends]];
self.searchResults = [[NSMutableArray alloc] init];
self.sections = [[NSMutableDictionary alloc] init];

BOOL found;

[self.sections setValue:[[NSMutableArray alloc] init] forKey:UITableViewIndexSearch];

// Loop through the friends and create our keys
for (NSDictionary *friend in self.fbFriends)
{
    NSString *c = [[friend objectForKey:@"name"] substringToIndex:1];

    found = NO;

    for (NSString *str in [self.sections allKeys])
    {
        if ([str isEqualToString:c])
        {
            found = YES;
        }
    }

    if (!found)
    {
        [self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
    }
}

// Loop again and sort the friends into their respective keys
for (NSDictionary *friend in self.fbFriends)
{
    [[self.sections objectForKey:[[friend objectForKey:@"name"] substringToIndex:1]] addObject:friend];
}

// Sort each section array
for (NSString *key in [self.sections allKeys])
{
    [[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]];
}

以下是我的部分设置和标题视图:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return 1;
    } else {
        return [[self.sections allKeys] count];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return NSLocalizedString(@"FbFriendsSearchControllerSection", @"Fb Friends search controller - section title for search results table view");
    } else {
        return [[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
    }
}

有人看到这是不正确的吗?

1 个答案:

答案 0 :(得分:0)

这不是标准做法。额外的部分不需要显示搜索。

请勿将“搜索”部分添加到self.sections字典中。相反,您只有实际数据的部分。然后,在tableView:sectionForSectionIndexTitle:atIndex:方法中,您可以执行以下操作:

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    NSInteger res = 0;
    if (tableView == self.tableView) {
        if (index == 0) {
            // If the user taps the search icon, scroll the table view to the top
            res = -1;
            [self.tableView setContentOffset:CGPointMake(0, 0) animated:NO];
        } else {
            res = ... // return the proper index for your data
        }
    } else {
        res = 0;
    }

    return res;
}

旁注 - 你真的想拥有一系列词典。主数组应代表各部分。正如您现在所拥有的那样,您不断获取主词典的密钥并对其进行排序。这将做很多次 - 都是不必要的。使用数组可以快速从段索引中获取数据。