这个最典型的就是电话本,然后根据A-Z分组, 当然很多例子,不过现在发现一个很简洁易懂的:

1. 准备数据,定义一个dictionary来显示所有的内容,这个dictionary对应的value全是数组

也就是:

A -> A1, A2...

B  -> B1, B2...

...

NSMutableDictionary *sections;

2. 创建所有的Keys

BOOL found;
// Loop through the books and create our keys
for (NSDictionary *book in self.books) //self.books 就是包含NSDictionary的数组
{
NSString *c = [[book objectForKey:@"title"] 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];
}
}

3. 把Key对应的空数组填满,这个很简单应该能看懂

for (NSDictionary *book in self.books)
{
[[self.sections objectForKey:[[book objectForKey:@"title"] substringToIndex:1]] addObject:book];
}

4. 下面就排序

for (NSString *key in [self.sections allKeys])
{
[[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES]]];
}

5. 有了上面的方法之后,就执行UITableView必须的方法

#pragma mark -
#pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.sections allKeys] count];
} - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count];
} - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
static NSString *CellIdentifier = @"Cell";
 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
 
NSDictionary *book = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
 
cell.textLabel.text = [book objectForKey:@"title"];
cell.detailTextLabel.text = [book objectForKey:@"description"];
 
return cell;
}

差不多了,这个是我见过最简洁的例子了。

参考:http://www.icodeblog.com/2010/12/10/implementing-uitableview-sections-from-an-nsarray-of-nsdictionary-objects/

05-11 22:02