UITableview右侧索引
右侧索引功能是iOS很常见的功能,在通讯录就得到了完美应用,在说这个功能之前,我们首先了解一个按首字母或者汉字拼音首字母分组排序索引的类。它能够根据地区来生成与之对应区域索引标题。不需要直接创建它的对象,我们可以通过 UILocalizedIndexedCollation +currentCollation
获得一个对应当前地区的单例对象。
UILocalizedIndexedCollation
UILocalizedIndexedCollation
的首要任务就是决定对于当前地区区域索引标题应该是什么,我们可以通过 sectionIndexTitles
属性来获得它们。
下面直接放代码:
- (void)setObjects:(NSArray *)objects {
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
NSInteger sectionTitlesCount = [[collation sectionTitles] count];
_mutableSections = [NSMutableArray arrayWithCapacity:sectionTitlesCount];
for (int i = 0; i < sectionTitlesCount; i++) {
NSMutableArray *subArr = [NSMutableArray array];
[_mutableSections addObject:subArr];
}
for (BeanModel *bean in _beanArr) {
NSInteger section = [collation sectionForObject:bean collationStringSelector:@selector(name)];
NSMutableArray *subArr = _mutableSections[section];
[subArr addObject:bean];
}
for (NSMutableArray *subArr in _mutableSections) {
NSArray *sortArr = [collation sortedArrayFromArray:subArr collationStringSelector:@selector(name)];
[subArr removeAllObjects];
[subArr addObjectsFromArray:sortArr];
}
}
UITableview显示右侧索引
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}
- (NSInteger)tableView:(UITableView *)tableView
sectionForSectionIndexTitle:(NSString *)title
atIndex:(NSInteger)index
{
return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}
修改右侧索引样式以及header title样式
//修改titleForHeaderInSection title的属性
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.contentView.backgroundColor= [UIColor colorWithRed:246/255.0 green:246/255.0 blue:246/255.0 alpha:1];
[header.textLabel setTextColor:[UIColor colorWithHexString:@"4778CC"]];
[header.textLabel setFont:[UIFont systemFontOfSize:15.f]];
}