当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS如何让tableview支持不同种类的cell详解

iOS如何让tableview支持不同种类的cell详解

2019年07月24日  | 移动技术网IT编程  | 我要评论

侗族的风俗习惯,中药葛根的功效,七年黑道生涯

前言

我们在项目中偶尔需要让tableview里支持不同种类的cell,比如微博的原创微博和别人转发的微博,就是两种cell。又或是类似支付宝的的timeline也有各种类型的cell。在同一个tableview里实现不同种类的cell,一般有两种方法,一种是把所有种类的cell先注册了,再根据不同的identifer去加载cell,一种是在init时创建不同的identifer的cell。

效果图如下:


准备工作

创建一个基类的cdzbasecell,基类cell拥有一些共用的属性和方法,如持有model,解析model。

创建不同的子类cell,以两个子类cdztypeacell cdztypebcell 为例,继承自cdzbasecell,重写一些方法,如高度,显示视图等等。

datasource中准备好判断index所在的cell种类的方法(如根据model的type属性等)

- (class)cellclassatindexpath:(nsindexpath *)indexpath{
 cdztableviewitem *item = [self itematindexpath:indexpath];
 switch (item.type) {
  case typea:{
   return [cdztypeacell class];
  }
   break;
  case typeb:{
   return [cdztypebcell class];
  }
   break;
 }
}

- (cdztableviewitem *)itematindexpath:(nsindexpath *)indexpath{
 return self.itemsarray[indexpath.row];
}

- (nsstring *)cellidentiferatindexpath:(nsindexpath *)indexpath{
 return nsstringfromclass([self cellclassatindexpath:indexpath]);
}

方法一:先注册,根据identifer去加载不同的cell

先在tableview创建时注册需要的不同种类,再判断index对应的种类,再根据identifer加载子类cell。

[self.tableview registerclass:[cdztypeacell class] forcellreuseidentifier:nsstringfromclass([cdztypebcell class])];
[self.tableview registerclass:[cdztypebcell class] forcellreuseidentifier:nsstringfromclass([cdztypebcell class])];

并在- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath中根据重用标识加载cell。

- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath{
 cdzbasecell *cell = [tableview dequeuereusablecellwithidentifier:[self cellidentiferatindexpath:indexpath] forindexpath:indexpath];
 cell.item = [self itematindexpath:indexpath];
 return cell;
}

方法二:在init时创建不同identifer的cell

- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath中判断cell是否为nil,并根据index所在cell的种类初始化cell和其identifer。

-(uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath{
 cdzbasecell *cell = [tableview dequeuereusablecellwithidentifier:[self cellidentiferatindexpath:indexpath]];
 if (!cell) {
  class cls = [self cellclassatindexpath:indexpath];
  cell = [[cls alloc]initwithstyle:uitableviewcellstyledefault reuseidentifier:[self cellidentiferatindexpath:indexpath]];
 }
 cell.item = [self itematindexpath:indexpath];
 return cell;
}

源码下载

所有源码和demo()

总结

个人更喜欢第二种,苹果官方文档也推荐第二种方法去重用cell。我觉得优点是一个是在tableview划分mvc架构时,tableview创建时不需要知道cell的类型,而只需要知道datasouce,而datasource才是需要去分配cell类型的。第二个是tableviewcell的初始化方法并非只能用initwithstyle(collectionview必须先注册的原因则在于初始化方法只有initwithframe)。而使用了注册,则是在复用池空时默认调用initwithstyle的方法,如果需要用别的方法初始化就不可以了。第一种方法可以用在有一些库需要先注册后才能调用的,比如自动计算cell高度的库fdtemplatelayoutcell。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网