今天做的小demo是实现类似于咱们iPhone上通讯录中的索引,非常简单,大家可以参考一下,有什么不对的地方还请指出!
索引要实现的方法- (NSArray )sectionIndexTitlesForTableView:(UITableView )tableView
**
plist文件
**
#import "ViewController.h"
//标识符
#define MARK @"carList"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)NSArray *listTeams;
@end
@implementation ViewController
//懒人加载数据
- (NSArray*)listTeams{
if (_listTeams == nil) {
_listTeams = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cars_total" ofType:@"plist"]];
}
return _listTeams;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark --设置组count
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [self listTeams].count;
}
#pragma mark --设置行count
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *rowArray = [self getDiction:section][@"cars"];
return rowArray.count;
}
#pragma mark 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MARK];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MARK];
}
NSArray *rowArray = [self getDiction:indexPath.section][@"cars"];
NSDictionary *rowDic = rowArray[indexPath.row];
cell.textLabel.text = rowDic[@"name"];
cell.imageView.image = [UIImage imageNamed:rowDic[@"icon"]];
return cell;
}
#pragma mark --设置组标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [self getDiction:section][@"title"];
}
#pragma mark --数据元协议设置索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
//设置索引数组
NSMutableArray *sectionIndex = [[NSMutableArray alloc] init];
//从数据中取得索引
for (NSDictionary *str in self.listTeams) {
[sectionIndex addObject:str[@"title"]];
}
//返回索引
return sectionIndex;
}
#pragma mark --取出plist中的字典
- (NSDictionary *)getDiction:(NSInteger)section{
return self.listTeams[section];
}
@end