IOS购物车tableview

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

@end

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

/** 代理属性*/
@property (nonatomic, weak) id 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];
    }
}

你可能感兴趣的:(IOS购物车tableview)