如何处理一个tableView中同种model多种cell相同逻辑的情况?
点击上方“iOS开发”,选择“置顶公众号”
关键时刻,第一时间送达!
IU的图片用完了,用我允的代替一下
这是购物车页面:
有4种cell:
1.一般商品cell
2.带赠品的商品cell
3.满赠商品cell
4.补货中商品cell
一般来说,有多少种cell就要自定义多少种cell,但是这4种cell又有相同的逻辑处理,如点击商品图片进入商品详情页。如何处理既不会让代码显得啰嗦又不会因为继承导致耦合度变高?
我的做法是先封装一个基类cell,这个cell只封装逻辑处理相关代码:
#import <UIKit/UIKit.h>
#import "CQShopCartCellModel.h"
@class CQShopCartGoodsCell;
@protocol CQShopCartGoodsCellDelegate <NSObject>
@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 <CQShopCartGoodsCellDelegate> 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开发整理发布,转载请联系作者授权