iOS Developer

本地化下按首字母分组排序的神器——UILocalizedInde

2017-02-26  本文已影响225人  云天大侠_general

0x01.引言

最近在整一个通讯录相关的项目,通讯录当然就少不了按首字母或者汉字拼音首字母分组排序索引。因为按照我一贯的的做法,都是想要做成更通用的、支持本地化的,所以这就纠结了,世界各地的语言啊我去,我顶多也就认识中文和英语,这就不能用以前的那些比如把汉字转成拼音再排序的方法了,效率不高不说,对其他国家的本地化更是行不通。一个偶然的机会,我才发现SDK里已经提供了一个实现此功能的神器——UILocalizedIndexedCollation

@interface Person : NSObject
@property(nonatomic, strong) NSString *name;
@end
 NSArray *srcArray = @[<林荣>, <林丹>, <周董>, <周树人>, <周杰伦>, <阿华>];

0x02. 先将UILocalizedIndexedCollation初始化,

UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];

0x03.Example

//得出collation索引的数量,这里是27个(26个字母和1个#)
NSInteger sectionTitlesCount = [[collation sectionTitles] count];

//初始化一个数组newSectionsArray用来存放最终的数据,我们最终要得到的数据模型应该形如:
//@[@[以A开头的数据数组],@[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]

NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    
//初始化27个空数组加入newSectionsArray
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [newSectionsArray addObject:array];
}
    
//将每个人按name分到某个section下

for (Person *p in srcArray) {
  //获取name属性的值所在的位置,比如"林丹",首字母是L,在A~Z中排第11(第一位是0),sectionNumber就为11
    NSInteger sectionNumber = [collation sectionForObject:p collationStringSelector:@selector(name)];
  //把name为“林丹”的p加入newSectionsArray中的第11个数组中去
    NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
    [sectionNames addObject:p]; 
}
    
//对每个section中的数组按照name属性排序
for (NSIntger index = 0; index < sectionTitlesCount; index++) {
    NSMutableArray *personArrayForSection = newSectionsArray[index];
    NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
    newSectionsArray[index] = sortedPersonArrayForSection;
}

0x04.后续工作

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [collation sectionTitles][section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [collation sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [collation sectionForSectionIndexTitleAtIndex:index];
}
上一篇 下一篇

猜你喜欢

热点阅读