如何处理一个tableView中同种model多种cell相同逻辑的情况?
点击上方“iOS开发”,选择“置顶公众号”
关键时刻,第一时间送达!


IU的图片用完了,用我允的代替一下
这是购物车页面:

有4种cell:
1.一般商品cell
2.带赠品的商品cell
3.满赠商品cell
4.补货中商品cell
一般来说,有多少种cell就要自定义多少种cell,但是这4种cell又有相同的逻辑处理,如点击商品图片进入商品详情页。如何处理既不会让代码显得啰嗦又不会因为继承导致耦合度变高?
我的做法是先封装一个基类cell,这个cell只封装逻辑处理相关代码:
#import
#import "CQShopCartCellModel.h"
@class CQShopCartGoodsCell;
@protocol CQShopCartGoodsCellDelegate
@optional
/** 选中按钮点击 */
- (void)goodsCell:(CQShopCartGoodsCell *)goodsCell chooseButtonDidClick:(UIButton *)chooseButton;
/** 加按钮点击 */
- (void)goodsCell:(CQShopCartGoodsCell *)goodsCell addButtonDidClick:(UIButton *)addButton;
/** 减按钮点击 */
- (void)goodsCell:(CQShopCartGoodsCell *)goodsCell minusButtonDidClick:(UIButton *)minusButton;
/** 商品图片点击 */
- (void)goodsCell:(CQShopCartGoodsCell *)goodsCell goodsImageViewDidTap:(UIImageView *)goodsImageView;
@end
@interface CQShopCartGoodsCell : UITableViewCell
@property (nonatomic, weak) id
delegate; @property (nonatomic, strong) CQShopCartCellModel *model;
@end
然后4种cell再继承这个基类cell。
在controller中:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CQShopCartGoodsCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:@""];
CQShopCartCellModel *model = nil;
switch (indexPath.section) {
case 0: // 普通商品
{
model = self.commonGoodsArray[indexPath.row];
if (goodsCell == nil) {
if (model.giftsArray.count > 0) {
// 有赠品的商品
goodsCell = [[CQShopCartHaveGiftGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CQShopcartHaveGiftGoodsCellID];
} else {
// 无赠品的商品
goodsCell = [[CQShopCartNoGiftGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CQShopcartNoGiftGoodsCellID];
}
}
}
break;
case 1: // 满赠商品
{
model = self.giftGoodsArray[indexPath.row];
goodsCell = (goodsCell ?: [[CQShopCartGiftGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CQShopcartGiftGoodsCellID]);
}
break;
case 2: // 补货中商品
{
model = self.emptyGoodsArray[indexPath.row];
goodsCell = (goodsCell ?: [[CQShopCartEmptyGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CQShopcartEmptyGoodsCellID]);
}
break;
default:
break;
}
goodsCell.model = model;
goodsCell.delegate = self;
return goodsCell;
}

一目了然。
欢迎大家说出自己的想法。

作者:无夜之星辰
链接:http://www.jianshu.com/p/f308c43fb459
iOS开发整理发布,转载请联系作者授权
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号随时掌握互联网精彩
- 1 习近平将发表二〇二六年新年贺词 7904141
- 2 2026年国补政策来了 7808738
- 3 东部战区:开火!开火!全部命中! 7712893
- 4 2026年这些民生政策将惠及百姓 7616985
- 5 小学食堂米线过期2.5小时被罚5万 7519709
- 6 解放军喊话驱离台军 原声曝光 7428214
- 7 为博流量直播踩烈士陵墓?绝不姑息 7327605
- 8 每月最高800元!多地发放养老消费券 7238391
- 9 数字人民币升级 1月1日起将计付利息 7141831
- 10 2026年1月1日起 一批新规将施行 7040675











iOS开发
