史上最简洁的UITableView Sections 展示包含NSDicionary 的NSArray
这个最典型的就是电话本,然后根据A-Z分组, 当然很多例子,不过现在发现一个很简洁易懂的:
1. 准备数据,定义一个dictionary来显示所有的内容,这个dictionary对应的value全是数组
也就是:
A -> A1, A2...
B -> B1, B2...
...
1 | NSMutableDictionary *sections; |
2. 创建所有的Keys
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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对应的空数组填满,这个很简单应该能看懂
1 2 3 4 | for (NSDictionary *book in self.books) { [[self.sections objectForKey:[[book objectForKey: @"title" ] substringToIndex:1]] addObject:book]; } |
4. 下面就排序
1 2 3 4 | for (NSString *key in [self.sections allKeys]) { [[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey: @"title" ascending :YES]]]; } |
5. 有了上面的方法之后,就执行UITableView必须的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #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; } |
差不多了,这个是我见过最简洁的例子了。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步