温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

iOS怎么让tableview支持不同种类的cell

发布时间:2021-02-20 11:47:15 来源:亿速云 阅读:431 作者:小新 栏目:移动开发

这篇文章主要介绍了iOS怎么让tableview支持不同种类的cell,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

前言

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

效果图如下:

iOS怎么让tableview支持不同种类的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”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI