iOS tableView无序渲染不同样式的cell

在创建tableView时,有时候需要加载好多种不同样式的自定义cell,这时候根据indexPath.section = 0、1、2、3、4,这样不能满足服务器数据的动态变化是小事,关键显得自己特别的初级。
那么应该如何动态根据服务器返回的数据渲染对应的自定义cell呢?咱一步一步来。

  • 首先numberOfSectionsInTableView里一如既往;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return arr.count;
}
  • numberOfSectionsInTableView里一如既往;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return subArray.count;
}
  • heightForRowAtIndexPath里;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BBmodle * modle = arr[indexPath.section];
   if ([modle.key isEqualToString:@"cell1"]) {

        return 90;
        
    }else if([modle.key isEqualToString:@"cell2"]){

        return 78;
        
    }else if([modle.key isEqualToString:@"cell3"]){

        return 114;      
    }
  return 0;
}
  • cellForRowAtIndexPath里;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BBmodle * modle = arr[indexPath.section];
    if ([modle.key isEqualToString:@"cell1"]) {
        
        //cell1
        XXCell1 *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        if (!cell) {
            cell = [[XSWorkTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
        }
        return cell;
        
    }else if([modle.key isEqualToString:@"cell2"]){
        
        //cell2
        XXCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        return cell;
        
    }else if([modle.key isEqualToString:@"cell3"]){
        
        //cell3
        XXCell3 *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        if (!cell) {
            cell = [[XSAreaSevTableViewCell alloc]init];
        }
        return cell;        
    }
 return [UITableViewCell new];
}

说明:arr 里装BBmodle模型,BBmodle模型中包含一个key,对应模型的唯一标识,亦或者对应cell的样式标识;还包含一个subArray,这个模型下的数组。

如此以来,我们大可以直接加载服务器返回的所有数据,而不用去管数组的顺序变化、以及数量变化了。是不是代码逻辑清晰了很多,而且一劳永逸。

大概样式及效果:

!
WechatIMG38.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概述在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似...
    liudhkk阅读 9,091评论 3 38
  • 在使用tableview 前 记得设置 Delegate 和DataSource UITableView = _T...
    谁说_阅读 1,732评论 0 1
  • iOS 实战开发课程笔记 本贴旨在作为对极客班 《iOS 开发实战》第五期期课程视频重新学习的笔记。目标是建立一个...
    黄穆斌阅读 3,097评论 12 57
  • 一、简介 <<UITableView(或简单地说,表视图)的一个实例是用于显示和编辑分层列出的信息的一种手段 <<...
    无邪8阅读 10,692评论 3 3
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,603评论 28 53