美文网首页iOS开发好文iOS OC 学习手册tableview和cell相关
iOS中无序多数据按索引自动分类和排列

iOS中无序多数据按索引自动分类和排列

作者: 哈哈大p孩 | 来源:发表于2016-07-12 10:41 被阅读1802次

    最近用美团购物的时候,发现了我们常用的tableview的索引情况,之前没怎么研究过索引,只知道是系统自带的方法,应该很简单的,然后动手去写了一下,倒是发现了一个问题:基本索引很简单,直接调系统的方法,然而涉及到多样化的数据时候,如何让数据自动分类以及排序就是个问题。然后动手呗,先百度找些资料,发现很多都说的不全面,而且杂乱无章,也看不明白,花了一下午时间,自己总算整理出来一些心得,并写了个demo,复用性蛮高的,现在贴下来。
    新建User类,继承NSObject
    User.h

    -(id)init:(NSString*) _username name:(NSString*) _name;
    @property (assign, readwrite, nonatomic) NSString *name;
    @property (assign, readwrite, nonatomic) NSString *username;
    

    User.m

    @synthesize name,username;
    -(id)init:(NSString*) _username name:(NSString*) _name {
        self = [super init];
        self.username = _username;
        self.name = _name;
        
        return self;
    }
    

    然后回到ViewController中,在.h文件中

    @interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
    @property (nonatomic, strong) NSMutableArray *userArray; //数据源数组
    @property (nonatomic, strong) NSMutableArray *sectionsArray;//存放section对应的userObjs数组数据
    
    //UITableView索引搜索工具
    @property (nonatomic, strong) UILocalizedIndexedCollation *collation;
    

    ViewController.m中
    重点:UILocalizedIndexedCollation类

    //配置分组信息
    - (void)configureSections {
       //初始化测试数据
        NSMutableArray *city = [[NSMutableArray alloc] init];
        _userArray = [NSMutableArray arrayWithObjects:@"北京",@"安徽",@"合肥",@"邯郸",@"蚌埠",@"上海",@"广州",@"西安",@"淮南",@"江西",@"武汉",@"广西",@"河北",@"俄罗斯",@"盐城",@"江苏",@"新疆",@"乌鲁木齐", nil]; 
    //项目集成时候,也就把这里的_userArray数据源换一下,其他代码用我的不变即可,就可快速按照索引排序和分类
        for (int i = 0; i < _userArray.count; i++) {
            [city addObject:[[User alloc] init:_userArray[i] name:_userArray[i]]];
        }
    
        
        
        //获得当前UILocalizedIndexedCollation对象并且引用赋给collation,A-Z的数据
        self.collation = [UILocalizedIndexedCollation currentCollation];
        
        //获得索引数和section标题数
        NSInteger index, sectionTitlesCount = [[_collation sectionTitles] count];
        
        //临时数据,存放section对应的userObjs数组数据
        NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
        
        //设置sections数组初始化:元素包含userObjs数据的空数据
        for (index = 0; index < sectionTitlesCount; index++) {
            NSMutableArray *array = [[NSMutableArray alloc] init];
            [newSectionsArray addObject:array];
        }
        
        //将用户数据进行分类,存储到对应的sesion数组中
        for (User *userObj in city) {
            
            //根据timezone的localename,获得对应的的section number
            NSInteger sectionNumber = [_collation sectionForObject:userObj collationStringSelector:@selector(username)];
            
            //获得section的数组
            NSMutableArray *sectionUserObjs = [newSectionsArray objectAtIndex:sectionNumber];
            
            //添加内容到section中
            [sectionUserObjs addObject:userObj];
        }
        
        //排序,对每个已经分类的数组中的数据进行排序,如果仅仅只是分类的话可以不用这步
        for (index = 0; index < sectionTitlesCount; index++) {
            
            NSMutableArray *userObjsArrayForSection = [newSectionsArray objectAtIndex:index];
            
            //获得排序结果
            NSArray *sortedUserObjsArrayForSection = [_collation sortedArrayFromArray:userObjsArrayForSection collationStringSelector:@selector(username)];
            
            //替换原来数组
            [newSectionsArray replaceObjectAtIndex:index withObject:sortedUserObjsArrayForSection];
        }
        self.sectionsArray = newSectionsArray;
    }
    

    delegate

    #pragma mark -- delegate
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        // The number of sections is the same as the number of titles in the collation.
        return [[_collation sectionTitles] count];
        
    }
    
    //设置每个Section下面的cell数
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        
        // The number of time zones in the section is the count of the array associated with the section in the sections array.
        NSArray *UserObjsInSection = [_sectionsArray objectAtIndex:section];
        
        return [UserObjsInSection count];
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier = @"Cell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        
        // Get the time zone from the array associated with the section index in the sections array.
        NSArray *userNameInSection = [_sectionsArray objectAtIndex:indexPath.section];
        
        // Configure the cell with the time zone's name.
        User *userObj = [userNameInSection objectAtIndex:indexPath.row];
        cell.textLabel.text = userObj.username;
        
        return cell;
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    
    /*
     * 跟section有关的设定
     */
    //设置section的Header
    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
        NSArray *UserObjsInSection = [_sectionsArray objectAtIndex:section];
        if(UserObjsInSection == nil || [UserObjsInSection count] <= 0) {
            return nil;
        }
        return [[_collation sectionTitles] objectAtIndex:section];
    }
    //设置索引标题
    - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
        return [_collation sectionIndexTitles];
    }
    //关联搜索
    - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
        return [_collation sectionForSectionIndexTitleAtIndex:index];
    }
    

    当然了,一开始我们还要创建tableview,这里就不写了,然后调用最上面那个重要方法configureSections(我都集成好了,读者可以直接对数据源做操作,即可),效果图如下:

    Paste_Image.png

    有的小伙伴想下载源码,博主最近正在研究github(之前没用过..),稍后会贴出地址。
    如果你也喜欢的话,点个赞吧。

    相关文章

      网友评论

      • FreeSnow:这个索引,列表没有某个字母开头的话没,应该不让他显示,对不对。
      • qazws:qiu demo
        哈哈大p孩:@sp5 抱歉,最近才把代码上传到github上,地址:https://github.com/Feijunjie/IndexDemo/tree/master

      本文标题:iOS中无序多数据按索引自动分类和排列

      本文链接:https://www.haomeiwen.com/subject/uyjjjttx.html