IOS之表视图添加索引
我们要实现的效果如下。
?
?
?
1.修改ControlView.h,即添加变量dict,用于存储TabelView的数据源。
?3.初始化TableView
//分为多少个分组- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{return [[dict allKeys] count];}//每个分组的数据单元个数- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ switch(section) { case 0: { return [[dict objectForKey:@"Group1"] count]; } case 1: { return [[dict objectForKey:@"Group2"] count]; } case 2: { return [[dict objectForKey:@"Group3"] count]; } } return 0;}//分组的标题,不实现下面的方法,不显示分组标题- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ //dict allKeys取出的key arr无顺序,需进行排序 NSArray *arr = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)];return [arr objectAtIndex:section];}//列表右侧的索引提示,不实现下面的方法,不显示右侧索引-(NSArray *) sectionIndexTitlesForTableView: (UITableView *) tableView{ //dict allKeys取出的key arr无顺序,需进行排序 NSArray *arr = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)]; return arr;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"myTableCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; NSUInteger row = [indexPath row]; NSUInteger section = [indexPath section]; NSArray *arr; switch (section) { case 0: arr = [dict objectForKey:@"Group1"]; break; case 1: arr = [dict objectForKey:@"Group2"]; break; case 2: arr = [dict objectForKey:@"Group3"]; break; default: break; } NSDictionary *rowDict = [arr objectAtIndex:row]; cell.textLabel.text = [rowDict objectForKey:@"itemName"]; NSLog(@"cell.label.text = %@",[rowDict objectForKey:@"itemName"]); NSString *imagePath = [rowDict objectForKey:@"itemImagePath"]; cell.imageView.image = [UIImage imageNamed:imagePath]; NSLog(@"cell.image.image = %@",imagePath); cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell;}//选中Cell响应事件- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失 NSUInteger row = [indexPath row]; NSUInteger section = [indexPath section]; NSArray *arr; switch (section) { case 0: arr = [dict objectForKey:@"Group1"]; break; case 1: arr = [dict objectForKey:@"Group2"]; break; case 2: arr = [dict objectForKey:@"Group3"]; break; default: break; } NSDictionary *rowDict = [arr objectAtIndex:row]; NSString *userName = [rowDict objectForKey:@"itemName"]; NSLog(@"userName=%@",userName);}?
?