0
点赞
收藏
分享

微信扫一扫

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

舍予兄 2021-09-19 阅读 154
日记本

在创建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];
}

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

大概样式及效果:

!

举报

相关推荐

0 条评论