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