在做类似通讯录相关的功能时会用到tableView的索引,一个section会在一个索引目录中。通常会把联系人第一个字的首字母作为一个索引。点击对应索引,tableView会自动跳转到对应的section。
设置索引背景色:
_tableView.sectionIndexBackgroundColor=[UIColor clearColor];
设置索引文字颜色:
_tableView.sectionIndexColor=[UIColor blackColor];
每个分区的页眉:
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return self.keys[section];//keys为页眉数组
}
索引目录:
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return self.keys;
}
如果你的tableView没有设置tableHeaderView的话索引的点击代理方法是不用重写的,点击会自动跳转到对应的section。但是如果设置的话,点击最上面的索引就会出现一些问题,例如一个搜索框作为tableHeaderView时,索引目录对应添加了搜索的icon:
这样当你点击搜索icon时tableView会自动跳转到滴0个section也就是这里的’B’分区而不是搜索框的tableHeaderView,这就需要进行处理,当点击第0个索引是设置tableView的offset,使之偏移到最上面:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
if (index == 0) {
[tableView setContentOffset:CGPointMake(0, 0) animated:NO];
return -1;
}
return index;
}