iOS UITableView(九) 给tableView添加索引

本文介绍如何给tableView添加右侧索引主要是用到了下面的方法

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

下面展示我的全代码

#import "ViewController.h"

@interface ViewController ()
{
    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
下面是效果

iOS UITableView(九) 给tableView添加索引_第1张图片

你可能感兴趣的:(UITableView)