1、索引其实很简单,只要实现下面(UITableViewDataSource中)这两个函数即可
// Index
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView; // return list of section titles to display in section index view (e.g. "ABCD...Z#")
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index; // tell table which section corresponds to section title/index (e.g. "B",1))
下面直接看代码:
#import "ViewController.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
{
UITableView * _tableView;
NSMutableArray * _dataArray;
NSMutableArray * _letterArray;
NSMutableArray * _indexArray;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
_dataArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 26; i++) {
NSMutableArray * array = [[NSMutableArray alloc] init];
for (int j = 0; j < 2; j++) {
NSString * str = [NSString stringWithFormat:@"%i行,%i列", i, j];
[array addObject:str];
}
[_dataArray addObject:array];
}
_letterArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 26; i++) {
[_letterArray addObject:[NSString stringWithFormat:@"%c", i + 'A']];
}
_indexArray = [[NSMutableArray alloc] init];
[_indexArray addObject:@"#"];
[_indexArray addObjectsFromArray:_letterArray];
[_indexArray addObject:@"*"];
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
[self.view addSubview:_tableView];
_tableView.dataSource = self;
_tableView.delegate = self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return _dataArray.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return _letterArray[section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_dataArray[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * cellid = @"cellid";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
}
cell.textLabel.text = _dataArray[indexPath.section][indexPath.row];
return cell;
}
//返回索引列表的字符值,查看源码可知数组必须是NSString类型
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return _indexArray;
}
//设置索引的序号和tableView的分区之间的对应关系
//确定点击某一个索引,跳转到哪一个对应的分区
//返回值对与其相等的section
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
if (index == 0) {
return 0;
}
if (index == 27) {
return 25;
}
return index - 1;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
效果: