小程序开发|小程序制作|小程序开发网

搜索

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

2021-11-2 14:32| 发布者: huxiaoqi| 查看: 233| 评论: 2

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

在创建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,这个模型下的数组。

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

大概样式及效果:

!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

鲜花

握手

雷人

路过

鸡蛋
发表评论

最新评论

引用 xiaoxiao 2022-9-26 14:53
你这也很僵硬呀
引用 admin 2022-3-7 02:25
可以

查看全部评论(2)

返回顶部