IOS购物车tableview

IMG_4721.PNG
  • 创建一个继承于tableViewCell的子类WineCell,在.h创建一个代理,在点击加号或者减号的时候,通知代理来实时改变总价,
@class Wine ,WineCell;
@protocol WineCellDelegate <NSObject>
@optional
- (void)wineCellDidClickPlusButton:(WineCell *)cell;
- (void)wineCellDidClickMinusButton:(WineCell *)cell;

@end

@interface WineCell : UITableViewCell
/** 模型*/
@property (nonatomic, strong) Wine *wine;

/** 代理属性*/
@property (nonatomic, weak) id<WineCellDelegate> delegate;

@end
  • .m中
- (IBAction)plusButtonClick {
    // 1.修改模型
    self.wine.count ++ ;
    // 2.修改界面
    self.countLabel.text = [NSString stringWithFormat:@"%d",self.wine.count];
    // 3.减号按钮能点击
    self.minusButton.enabled = YES;
    // 4.通知代理(调用代理的方法)
    if ([self.delegate respondsToSelector:@selector(wineCellDidClickPlusButton:)]) {
        [self.delegate wineCellDidClickPlusButton:self];
    }
}
/**
 *  减号点击
 */
- (IBAction)minusButtonClick {
    // 1.修改模型
    self.wine.count -- ;
    // 2.修改界面
    self.countLabel.text = [NSString stringWithFormat:@"%d",self.wine.count];
    // 3.控制减号按钮是否能点击
    if (self.wine.count == 0) {
        self.minusButton.enabled = NO;
    }
    // 4.通知代理(调用代理的方法)
    if ([self.delegate respondsToSelector:@selector(wineCellDidClickMinusButton:)]) {
        
        [self.delegate wineCellDidClickMinusButton:self];
    }
}
#pragma mark - WineCellDelegate
- (void)wineCellDidClickPlusButton:(WineCell *)cell
{
    // 计算总价
    int totalPrice = self.totalPriceLabel.text.intValue + cell.wine.money.intValue;
    // 设置总价
    self.totalPriceLabel.text = [NSString stringWithFormat:@"%d",totalPrice];
    // 购买按钮一定能点击
    self.buyButton.enabled = YES;
    
    // 之前没有添加过,才添加
    if (![self.shoppingCar containsObject:cell.wine]) {
        [self.shoppingCar addObject:cell.wine];
    }
}

- (void)wineCellDidClickMinusButton:(WineCell *)cell
{
    // 计算总价
    int totalPrice = self.totalPriceLabel.text.intValue - cell.wine.money.intValue;
    // 设置总价
    self.totalPriceLabel.text = [NSString stringWithFormat:@"%d",totalPrice];
    // 购买按钮是否能点击
    self.buyButton.enabled = totalPrice > 0;
    // 移除用户不需要在买的酒
    if (cell.wine.count == 0) {
        [self.shoppingCar removeObject:cell.wine];
    }
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容