表视图中的侧索引
更新:HHH   时间:2023-1-7


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    //创建tableview

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

    tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);

    tableView.dataSource = self;

    tableView.delegate = self;

    [self.view addSubview:tableView];

    //设置索引字体的颜色

    tableView.sectionIndexColor = [UIColor greenColor];

    //设置索引背景颜色

    tableView.sectionIndexBackgroundColor = [UIColor redColor];

    //设置点击后索引背景的颜色

    tableView.sectionIndexTrackingBackgroundColor = [UIColor blackColor];

    //获取文件路径

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ListData" ofType:@"plist"];

    self.dataDic = [NSDictionary dictionaryWithContentsOfFile:filePath];

    allKeys = [self.dataDic allKeys];

    

    //排序

    allKeys = [allKeys sortedArrayUsingSelector:@selector(compare:)];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


//返回组数

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return allKeys.count;

}

//返回每组的行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    NSArray *cellArray =[self.dataDic objectForKey:allKeys[section]] ;

    return cellArray.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *identifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];

    }

    NSArray *cellArray =[self.dataDic objectForKey:allKeys[indexPath.section]] ;

    cell.textLabel.text = [cellArray objectAtIndex:indexPath.row];

    return cell;

}


//section标题

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    return allKeys[section];

}


//索引

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

{

    return allKeys;

}


- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index

{

    return index;

}



返回开发技术教程...