这篇文章主要介绍了iOS怎么让tableview支持不同种类的cell,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
创新互联主营西乌珠穆沁网站建设的网络公司,主营网站建设方案,重庆APP开发公司,西乌珠穆沁h5微信小程序开发搭建,西乌珠穆沁网站营销推广欢迎西乌珠穆沁等地区企业咨询前言
我们在项目中偶尔需要让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;
}感谢你能够认真阅读完这篇文章,希望小编分享的“iOS怎么让tableview支持不同种类的cell”这篇文章对大家有帮助,同时也希望大家多多支持创新互联建站,关注创新互联网站建设公司行业资讯频道,更多相关知识等着你来学习!
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享名称:iOS怎么让tableview支持不同种类的cell-创新互联
网页路径:http://www.cqwzjz.cn/article/cdopso.html


咨询
建站咨询
