索引
索引使用原則
-索引標(biāo)題不能與顯示的標(biāo)題完全一樣
-索引標(biāo)題應(yīng)具有代表性,能代表一個(gè)數(shù)據(jù)集合
-如果采用了索引列表視圖,一般情況下就不再使用擴(kuò)展視圖
plist文件格式
代碼
#import "ViewController.h"
@interface ViewController ()
/** 從plist文件中讀取的數(shù)據(jù) */
@property (nonatomic, strong) NSDictionary *dictData;
/** 小組名 */
@property (nonatomic, strong) NSArray *listGroupname;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"team_dictionary" ofType:@"plist"];
//獲得plist文件中的全部數(shù)據(jù)
self.dictData = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSArray *tempArray = [self.dictData allKeys];
//對(duì)key進(jìn)行排序
self.listGroupname = [tempArray sortedArrayUsingSelector:@selector(compare:)];
}
#pragma mark - UITableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//按照節(jié)索引從小組名數(shù)組中獲得組名
NSString *groupName = [self.listGroupname objectAtIndex:section];
//組名為Key,從字典中取出球隊(duì)數(shù)組的集合
NSArray *listTeams = [self.dictData objectForKey:groupName];
return listTeams.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.listGroupname.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *groupName = [self.listGroupname objectAtIndex:section];
return groupName;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//按照節(jié)索引,從小組名數(shù)組中獲得組名
NSString *groupName = [self.listGroupname objectAtIndex:indexPath.section];
//按照組名為key,從字典中取出球隊(duì)數(shù)組集合
NSArray *listTeams = [self.dictData objectForKey:groupName];
cell.textLabel.text = [listTeams objectAtIndex:indexPath.row];
return cell;
}
//顯示側(cè)方索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSMutableArray *listTitles = [[NSMutableArray alloc] initWithCapacity:[self.listGroupname count]];
//去掉字段中的“組”字
for (NSString *item in self.listGroupname)
{
NSString *title = [item substringToIndex:1];
[listTitles addObject:title];
}
return listTitles;
}
@end