如何处理一个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 促进民营经济健康发展高质量发展 7953565
- 2 特朗普希望中国领导人访美 中方回应 7978612
- 3 2025年8省份将不再分文理科 7889832
- 4 高水平对外开放再升级 7703454
- 5 国产剧告别“假穷人” 7611286
- 6 土拨鼠为什么会突然大叫 7500766
- 7 女子抱孩子深夜投河 孩子仅两岁 7485086
- 8 工作室辟谣胡歌得肺癌住院 7331868
- 9 男子时隔6年回老家发现老猫还在守家 7220901
- 10 网红越野唐僧疑熬夜直播后去世 7164552