iOS 使用UILocalizedIndexedCollatio

2018-04-11  本文已影响55人  困惑困惑困惑

原文链接:http://www.cnblogs.com/pretty-guy/p/4831586.html
 UITableView在行数相当多的时候,给人的感觉是非常笨重的。通常为了方便用户使用,采用的方法有:搜索框、按层级展示、区域索引标题。

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

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

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

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

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">//根据SEL方法返回的字符串判断对象应该处于哪个分区

具体使用方法如下:

1.构造数据源

[ 复制代码

](javascript:void(0); "复制代码")

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">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];
}</pre>
[ 复制代码

](javascript:void(0); "复制代码")

2.实现TableViewDataSource

[ 复制代码

](javascript:void(0); "复制代码")

<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">#pragma mark SectionTitles

[ 复制代码

](javascript:void(0); "复制代码")

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

标签: IOS

[好文要顶](javascript:void(0);) [关注我](javascript:void(0);) [收藏该文](javascript:void(0);) [ image ](javascript:void(0); "分享至新浪微博") [ image ](javascript:void(0); "分享至微信")

image

pretty guy
关注 - 16
粉丝 - 28

最新评论

阅读排行榜

评论排行榜

推荐排行榜

Copyright ©2018 pretty guy

上一篇 下一篇

猜你喜欢

热点阅读