iOS 使用UILocalizedIndexedCollation实现区域索引标题(Section Indexed Title)即拼音排序

  UITableView在行数相当多的时候,给人的感觉是非常笨重的。通常为了方便用户使用,采用的方法有:搜索框、按层级展示、区域索引标题。

  前两种就不用介绍了,此文就介绍区域索引标题的实现。

  区域索引标题可以在通讯录里看到,类似这样:

区域索引标题可以通过转拼音实现,本文主要介绍使用UILocalizedIndexedCollation实现区域索引标题

 

UILocalizedIndexedCollation是苹果贴心为开发者提供的排序工具,会自动根据不同地区生成索引标题

//根据SEL方法返回的字符串判断对象应该处于哪个分区
- (NSInteger)sectionForObject:(id)object collationStringSelector:(SEL)selector;

//根据SEL方法返回的string对数组元素排序
- (NSArray *)sortedArrayFromArray:(NSArray *)array collationStringSelector:(SEL)selector;

 

具体使用方法如下:

1.构造数据源

NSArray *testArr = @[@"悟空",@"沙僧",@"八戒", @"吴进", @"悟能", @"唐僧", @"诸葛亮", @"赵子龙",@"air", @"Asia", @"crash", @"basic", @"阿里郎"];
    
    NSMutableArray *personArr = [NSMutableArray arrayWithCapacity:testArr.count];
    for (NSString *str in testArr) {
        Person *person = [[Person alloc] initWithName:str];
        [personArr addObject:person];
    }
    
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    NSLog(@"%@", collation.sectionTitles);
    
    //1.获取获取section标题
    NSArray *titles = collation.sectionTitles;
    
    //2.构建每个section数组
    NSMutableArray *secionArray = [NSMutableArray arrayWithCapacity:titles.count];
    for (int i = 0; i < titles.count; i++) {
        NSMutableArray *subArr = [NSMutableArray array];
        [secionArray addObject:subArr];
    }
    
    //3.排序
    //3.1 按照将需要排序的对象放入到对应分区数组
    for (Person *person in personArr) {
        NSInteger section = [collation sectionForObject:person collationStringSelector:@selector(name)];
        NSMutableArray *subArr = secionArray[section];
        
        [subArr addObject:person];
    }
    
    //3.2 分别对分区进行排序
    for (NSMutableArray *subArr in secionArray) {
        NSArray *sortArr = [collation sortedArrayFromArray:subArr collationStringSelector:@selector(name)];
        [subArr removeAllObjects];
        [subArr addObjectsFromArray:sortArr];
    }

2.实现TableViewDataSource

#pragma mark SectionTitles
- (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];
}

demo地址:https://github.com/WuKongCoo1/UILocalizedIndexedCollationDemo

 

posted @ 2015-09-23 10:59  pretty guy  阅读(8382)  评论(0编辑  收藏  举报