如何处理一个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 中共中央召开党外人士座谈会 7904646
- 2 王毅:是可忍孰不可忍 7808786
- 3 贪污超11亿!白天辉被执行死刑 7712086
- 4 全国首艘氢电拖轮作业亮点多 7619357
- 5 河北沧州杀妻案男方被判死刑 7523170
- 6 水银体温计将于2026年禁产 7428598
- 7 日本地震致多人受伤 超10万人需避难 7333066
- 8 《大明王朝1566》逆袭成国产剧天花板 7234097
- 9 日本强震 高市早苗神色慌张一路小跑 7140125
- 10 “人造太阳”何以照进现实 7044553




iOS开发
