您的位置:首页 > 产品设计 > UI/UE

iOS UITableView(九) 给tableView添加索引

2016-01-06 17:28 375 查看
本文介绍如何给tableView添加右侧索引主要是用到了下面的方法

-(NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView{}


下面展示我的全代码

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
UITableView *_tableView;
NSMutableArray *_dataArr;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self creatData];
_tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
_tableView.delegate=self;
_tableView.dataSource=self;
[self.view addSubview:_tableView];
}
-(void)creatData{
_dataArr=[[NSMutableArray alloc]init];
for (int i=0; i<26; i++) {
NSMutableArray *arr=[[NSMutableArray alloc]init];

for (int j=0; j<10; j++) {
NSString *str=[NSString stringWithFormat:@"这是第%c组的第%d个标题",'A'+i,j];
[arr addObject:str];
}
[_dataArr addObject:arr];
}
}
#pragma mark -表格索引
//返回右侧索引标题数组
//这个标题的内容时和分区标题相对应
-(NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView{
NSMutableArray *arr=[[NSMutableArray alloc]init];
//创建26个索引标题
//标题尽量和分区相对应
[arr addObject:UITableViewIndexSearch];
for (int i = 0; i < 26; i++) {
NSString *str = [NSString stringWithFormat:@"%c",'A'+i];
[arr addObject:str];
}
return arr;
}
//设置 右侧索引标题 对应的分区索引

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
//cell右侧标题
NSLog(@"title:%@",title);
//右侧标题在右侧的索引
NSLog(@"index:%ld",index);

//返回 对应的分区索引
return index-1;
}
//cell 内容的向右缩进 级别
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
return 1;
}

#pragma mark uitableView代理
//返回多少组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return _dataArr.count;
}
//每个分区有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_dataArr[section] count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//创建复用标识符
static NSString *cellID =@"cellID";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
}
//填充cell
cell.textLabel.text=_dataArr[indexPath.section][indexPath.row];
return cell;
}
//设置头标
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [NSString stringWithFormat:@"这是第%c组",'A'+section];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
下面是效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: