购物车实现 <Block实现回调>
阅读原文时间:2023年07月11日阅读:2

效果图如下:

具体代码实现如下:

Model:

#import

@interface ShopCarModel : NSObject

@property (nonatomic, copy) NSString * goodsName;
@property (nonatomic, copy) NSString * goodsPrice;
@property (nonatomic, copy) NSString * goodsImage;
@property (nonatomic, assign) NSInteger goodsCount;
@property (nonatomic, assign) BOOL isSelected;

  • (instancetype)modelWithDictionary: (NSDictionary *)dictionary;

@end

#import "ShopCarModel.h"

@implementation ShopCarModel

  • (instancetype)modelWithDictionary: (NSDictionary *)dictionary{

    ShopCarModel *model = [[ShopCarModel alloc]init];
    [model setValuesForKeysWithDictionary:dictionary];
    return model;
    }

// 容错处理

  • (void)setValue:(id)value forUndefinedKey:(NSString *)key{

}
@end

Cell:

#import
@class ShopCarModel;

typedef void(^selectBlock)(NSIndexPath *indexPath); // 选择
typedef void(^deleteBlock)(NSIndexPath *indexPath); // 删除
typedef void(^addBlock)(NSIndexPath *indexPath); // 添加
typedef void(^subTractBlock)(NSIndexPath *indexPath); // 相减

@interface ShopCell : UITableViewCell

@property (nonatomic,copy) selectBlock selectedBlock;
@property (nonatomic,copy) deleteBlock deleteBlock;
@property (nonatomic,copy) addBlock addBlock;
@property (nonatomic,copy) subTractBlock subTractBlock;
@property (nonatomic,strong) ShopCarModel *model;
@property (nonatomic,strong) NSIndexPath *indexPath;

@end

#import "ShopCell.h"
#import "ShopCarModel.h"

@interface ShopCell ()

@property (nonatomic,strong)UIImageView * GoodsImageView;
@property (nonatomic,strong)UILabel * goodsNameLable;
@property (nonatomic,strong)UILabel * goodsPriceLable;
@property (nonatomic,strong)UITextField * goodsCountTextfield;
@property (nonatomic,strong)UIButton * selectedButton;
@property (nonatomic,strong)UIButton * deletButton;
@property (nonatomic,strong)UIButton * subtractButton;
@property (nonatomic,strong)UIButton * addButton;

@end

@implementation ShopCell

  • (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    [self createSubViews];
    }
    return self;
    }

  • (void)createSubViews{

    _selectedButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_selectedButton setImage:[UIImage imageNamed:@"radiobuttons_normal"] forState:UIControlStateNormal];
    [_selectedButton setImage:[UIImage imageNamed:@"radiobuttons_pressed"] forState:UIControlStateSelected];
    //原来选择框框太小经常点不到 就想了这个方法 放大按钮 不放大图片
    [_selectedButton setImageEdgeInsets:UIEdgeInsetsMake(, , , )];
    _selectedButton.frame = CGRectMake(, , , );
    _selectedButton.tag = ;
    [_selectedButton addTarget:self action:@selector(isselectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_selectedButton];

    _GoodsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_selectedButton.frame.origin.x + , , , )];
    _GoodsImageView.layer.cornerRadius = ;
    [self.contentView addSubview:_GoodsImageView];

    _goodsNameLable = [[UILabel alloc]initWithFrame:CGRectMake(_GoodsImageView.frame.origin.x + , , [UIScreen mainScreen].bounds.size.width - - _GoodsImageView.frame.origin.x - - , )];
    _goodsNameLable.textAlignment = NSTextAlignmentLeft;
    _goodsNameLable.font = [UIFont systemFontOfSize:];
    _goodsNameLable.textColor = [UIColor blackColor];
    _goodsNameLable.numberOfLines = ;
    [self.contentView addSubview:_goodsNameLable];

    _goodsPriceLable = [[UILabel alloc]initWithFrame:CGRectMake(_goodsNameLable.frame.origin.x, ,[UIScreen mainScreen].bounds.size.width - - _GoodsImageView.frame.origin.x - - , )];
    _goodsPriceLable.textAlignment = NSTextAlignmentLeft;
    _goodsPriceLable.textColor = [UIColor redColor];
    _goodsPriceLable.font = [UIFont systemFontOfSize:];
    _goodsPriceLable.numberOfLines = ;
    [self.contentView addSubview:_goodsPriceLable];

    _deletButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _deletButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - , , , );
    [_deletButton setTitle:@"删除" forState:UIControlStateNormal];
    [_deletButton setTitle:@"删除" forState:UIControlStateHighlighted];
    [_deletButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _deletButton.titleLabel.font = [UIFont systemFontOfSize:];
    [_deletButton addTarget:self action:@selector(deletButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _deletButton.tag = ;
    [self.contentView addSubview:_deletButton];

    _subtractButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_subtractButton setImage:[UIImage imageNamed:@"carSubtractSelect.png"] forState:UIControlStateNormal];
    [_subtractButton setImage:[UIImage imageNamed:@"carSubtractNamol.png"] forState:UIControlStateSelected];
    [_subtractButton setImage:[UIImage imageNamed:@"carSubtractNamol.png"] forState:UIControlStateHighlighted];
    [_subtractButton setImageEdgeInsets:UIEdgeInsetsMake(, , , )];
    _subtractButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - , , , );
    _subtractButton.titleLabel.font = [UIFont systemFontOfSize:];
    _subtractButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_subtractButton addTarget:self action:@selector(subStractButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _subtractButton.tag = ;
    [self.contentView addSubview:_subtractButton];

    _goodsCountTextfield = [[UITextField alloc]initWithFrame:CGRectMake(_subtractButton.frame.origin.x + , _subtractButton.frame.origin.y + , , )];
    _goodsCountTextfield.borderStyle = ;
    _goodsCountTextfield.textColor = [UIColor blackColor];
    _goodsCountTextfield.textAlignment = NSTextAlignmentCenter;
    _goodsCountTextfield.font = [UIFont systemFontOfSize:];
    _goodsCountTextfield.enabled = NO;
    [self.contentView addSubview:_goodsCountTextfield];

    _addButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _addButton.frame = CGRectMake(_goodsCountTextfield.frame.origin.x + + , _goodsCountTextfield.frame.origin.y - , , );
    [_addButton setImageEdgeInsets:UIEdgeInsetsMake(, , , )];
    [_addButton setImage:[UIImage imageNamed:@"carAddSelect.png"] forState:UIControlStateNormal];
    [_addButton setImage:[UIImage imageNamed:@"carAddNamol.png"] forState:UIControlStateSelected];
    [_addButton setImage:[UIImage imageNamed:@"carAddNamol.png"] forState:UIControlStateHighlighted];
    _addButton.titleLabel.font = [UIFont systemFontOfSize:];
    _addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_addButton addTarget:self action:@selector(addButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _addButton.tag = ;
    [self.contentView addSubview:_addButton];
    }

  • (void)setModel:(ShopCarModel *)model{

    _model = model;
    _GoodsImageView.image = [UIImage imageNamed:_model.goodsImage];
    _goodsNameLable.text = [NSString stringWithFormat:@"%@",_model.goodsName];
    _goodsNameLable.text = _model.goodsName;

    // 修改label不同颜色显示
    NSString * str = [NSString stringWithFormat:@"价格:¥%@",model.goodsPrice];
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
    NSRange range = [[attributeStr string]rangeOfString:@"价格:"];
    NSRange reviseRange = NSMakeRange(range.location, range.length);
    [attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:reviseRange];
    [_goodsPriceLable setAttributedText:attributeStr];

    // 判断最小值
    if (model.goodsCount < ) {
    _goodsCountTextfield.text = @"";
    }else{
    _goodsCountTextfield.text = [NSString stringWithFormat:@"%ld",(long)model.goodsCount];
    }
    // 选择的
    if (model.isSelected) {
    _selectedButton.selected = YES;
    [_selectedButton setImage:[UIImage imageNamed:@"radiobuttons_pressed@2x.png"] forState:UIControlStateSelected];
    }
    // 未选的
    else{
    _selectedButton.selected = NO;
    [_selectedButton setImage:[UIImage imageNamed:@"radiobuttons_normal@2x.png"] forState:UIControlStateNormal];
    }
    }

#pragma private method

  • (void)isselectButtonClick: (UIButton *)button{

    if (self.selectedBlock) {
    self.selectedBlock(self.indexPath);
    }
    }

  • (void)deletButtonAction: (UIButton *)button{

    if (self.deleteBlock) {
    self.deleteBlock(self.indexPath);
    }
    }

  • (void)subStractButtonAction: (UIButton *)button{

    if (self.subTractBlock) {
    self.subTractBlock(self.indexPath);
    }
    }

  • (void)addButtonAction: (UIButton *)button{

    if (self.addBlock) {
    self.addBlock(self.indexPath);
    }

}
@end

Controller :

//
// ViewController.m
// ShopingCar
//
// Created by 思 彭 on 16/8/17.
// Copyright © 2016年 思 彭. All rights reserved.
//

#import "ViewController.h"
#import "ZH_Button.h"
#import "ArrayDataSource.h"
#import "Masonry.h"
#import "ShopCarModel.h"
#import "ShopCell.h"
#import "DetailViewController.h"

static NSString *const identifier = @"cell";
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height

@interface ViewController ()
{
UIButton * allButton;
UILabel * moneyLable;
float priceNumber;
UIImageView * _backGrundImageView;
UIButton * balanceButton;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) ArrayDataSource *dataSource;

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的购物车";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self loadData];
    [self createTabelView];
    [self createBottomView];
    }

#pragma mark - SetUI

  • (void)createTabelView{

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(, , ScreenWidth, ScreenHeight - ) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = ;
    [self.view addSubview:self.tableView];

    // 注册cell
    [self.tableView registerClass:[ShopCell class] forCellReuseIdentifier:identifier];
    self.tableView.tableFooterView = [[UIView alloc]init];
    }

  • (void)createBottomView{

    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(, ScreenHeight - , ScreenWidth, )];
    [self.view addSubview:bottomView];

    //全选按钮
    allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    allButton.frame = CGRectMake(, , , );
    [allButton setImage:[UIImage imageNamed:@"radiobuttons_normal"] forState:UIControlStateNormal];
    [allButton setImage:[UIImage imageNamed:@"radiobuttons_pressed"] forState:UIControlStateSelected];
    allButton.titleLabel.font = [UIFont systemFontOfSize:];
    allButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [allButton addTarget:self action:@selector(allButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    allButton.selected = NO;
    [bottomView addSubview:allButton];

    UILabel * quanxuanLable = [[UILabel alloc]initWithFrame:CGRectMake(allButton.frame.origin.x + , allButton.frame.origin.y - , , )];
    quanxuanLable.text = @"全选";
    quanxuanLable.font = [UIFont systemFontOfSize:];
    quanxuanLable.textAlignment = NSTextAlignmentLeft;
    [bottomView addSubview:quanxuanLable];

    moneyLable = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2.0 - , allButton.frame.origin.y, , )];
    moneyLable.textColor = [UIColor redColor];
    NSString * textStr = @"合计:¥0.00";
    NSMutableAttributedString * attributedStr = [[NSMutableAttributedString alloc]initWithString:textStr];
    NSRange range = [[attributedStr string]rangeOfString:@"合计:"];
    NSRange lastRange = NSMakeRange(range.location, range.length);
    [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:lastRange];
    [moneyLable setAttributedText:attributedStr];
    moneyLable.font = [UIFont systemFontOfSize:];
    moneyLable.textAlignment = NSTextAlignmentCenter;
    [bottomView addSubview:moneyLable];

    //结算按钮
    balanceButton = [UIButton buttonWithType:UIButtonTypeSystem];
    balanceButton.frame = CGRectMake(ScreenWidth - , , , );
    balanceButton.backgroundColor = [UIColor redColor];
    [balanceButton setTitle:@"结算" forState:UIControlStateNormal];
    [balanceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    balanceButton.titleLabel.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:];
    //字体祖后面加-Bold就是加粗 加-Oblique就是倾斜
    [balanceButton addTarget:self action:@selector(balanceButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:balanceButton];

    _backGrundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2.0 - , self.view.frame.size.height/2.0 - , , )];
    _backGrundImageView.image = [UIImage imageNamed:@"购物车空"];
    _backGrundImageView.hidden = YES;
    [bottomView addSubview:_backGrundImageView];

}

#pragma mark - loadData

  • (void)loadData{

    //设置购物车的模拟数据
    for (int i = ; i < ; i++) {
    NSMutableDictionary * dataDic = [[NSMutableDictionary alloc]init];
    NSString * nameStr = [NSString stringWithFormat:@"商品名称%d",i];
    NSString * priceStr = [NSString stringWithFormat:@"%.1f",199.0 + i];
    [dataDic setValue:nameStr forKey:@"goodsName"];
    [dataDic setValue:priceStr forKey:@"goodsPrice"];
    [dataDic setValue:@"kiutCat.png" forKey:@"goodsImage"];
    [dataDic setValue:@"" forKey:@"goodsCount"];
    ShopCarModel * model = [ShopCarModel modelWithDictionary:dataDic];
    [self.dataArray addObject:model];
    }
    [self.tableView reloadData];

}

#pragma mark - UITableView DataSource

  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.dataArray.count;
    }

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    __weak typeof(self) weakSelf = self;

    ShopCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.row];
    cell.indexPath = indexPath;

    cell.deleteBlock = ^ (NSIndexPath *indexPath){

    \[weakSelf.dataArray removeObjectAtIndex:indexPath.row\];  
    //重新计算价格  
    \[weakSelf sumOfAllPrice\];  
    // 带动画的删除该行  
    \[weakSelf.tableView deleteRowsAtIndexPaths:@\[indexPath\] withRowAnimation:UITableViewRowAnimationLeft\];  

    };
    cell.selectedBlock = ^ (NSIndexPath *indexPath){

    ShopCarModel \*model = weakSelf.dataArray\[indexPath.row\];  
    model.isSelected = !model.isSelected;  
    // 计算价钱 <记住要先选择再计算价钱>  
    \[weakSelf sumOfAllPrice\];  
    \[weakSelf.tableView reloadData\];  

    };
    cell.addBlock = ^ (NSIndexPath *indexPath){
    // 取得model
    ShopCarModel *model = weakSelf.dataArray[indexPath.row];
    if (model.goodsCount == ) {
    NSLog(@"不能再多啦!!!");
    [self showAlertView:@"不能再多啦!!!"];
    [weakSelf sumOfAllPrice];
    [weakSelf.tableView reloadData];
    }
    // 注意是 >= 1
    if (model.goodsCount >= ) {
    model.goodsCount++;
    [weakSelf sumOfAllPrice];
    [weakSelf.tableView reloadData];
    }
    };
    cell.subTractBlock = ^ (NSIndexPath *indexPath){

    // 取得model  
    ShopCarModel \*model = weakSelf.dataArray\[indexPath.row\];  
    if (model.goodsCount == ) {  
        NSLog(@"不能再少啦!!!");  
        \[self showAlertView:@"不能再少啦!!!"\];  
        return ;  // 让其不能再往下执行了  
    }  
    if (model.goodsCount < ) {  
       model.goodsCount = model.goodsCount - ;  
        \[weakSelf sumOfAllPrice\];  
        \[weakSelf.tableView reloadData\];  
    }  

    };
    return cell;
    }

#pragma mark - UITableView Delegate

  • (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    DetailViewController *detailVc = [[DetailViewController alloc]init];
    [self.navigationController pushViewController:detailVc animated:YES];
    }
    #pragma mark - private method

  • (void)showAlertView: (NSString *)messageStr{

    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提醒您哟!!!" message:messageStr delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];

}
// 全选

  • (void)allButtonClick: (UIButton *)button{

    // 取反
    button.selected = !button.selected;
    for (NSInteger i = ; i < self.dataArray.count; i++) {

    ShopCarModel \*model = self.dataArray\[i\];  
    model.isSelected = button.selected;  

    }
    //重新计算价钱
    [self sumOfAllPrice];
    [self.tableView reloadData];
    }

// 结算

  • (void)balanceButtonClick: (UIButton *)button{

    NSString *moneyStr = moneyLable.text;
    // 分割字符串
    NSArray *array = [moneyStr componentsSeparatedByString:@"合计:¥"];
    NSString *message;
    NSString *carStr;
    if (array.count == && [[array objectAtIndex:]floatValue] < 0.00000001) {
    message = @"请先选择商品哟!!!";
    carStr = @"请先选择商品哟!!!";
    }else{

    message = @"去结算";  
    carStr = \[NSString stringWithFormat:@"总计:%d元",\[\[array objectAtIndex:\] intValue\]\];  

    }
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:carStr message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
    }

  • (void)sumOfAllPrice{

    for (NSInteger i = ; i < self.dataArray.count; i++) {

    ShopCarModel \*model = self.dataArray\[i\];  
    if (model.isSelected) {  
        priceNumber = priceNumber + model.goodsCount \* \[model.goodsPrice floatValue\];  
    }  

    }
    NSString * moneyStr = [NSString stringWithFormat:@"合计:¥%0.2f",priceNumber];
    NSMutableAttributedString * attributedStr = [[NSMutableAttributedString alloc]initWithString:moneyStr];
    NSRange range = [[attributedStr string]rangeOfString:@"合计:"];
    NSRange lastRange = NSMakeRange(range.location, range.length);
    [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:lastRange];
    [moneyLable setAttributedText:attributedStr];
    moneyLable.text = [NSString stringWithFormat:@"合计:¥%0.2f",priceNumber];
    priceNumber = 0.0;

}

#pragma mark - 懒加载

  • (NSMutableArray *)dataArray{

    if (!_dataArray) {
    _dataArray = [NSMutableArray array];
    }
    return _dataArray;
    }

@end

刚开始有很多bug,不过应该,可能,大概解决了吧……<暂时没发现其他bug…嘿嘿嘿!!!>

最近有点闲,有点迷茫~~还是要加油,依旧要努力~~

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章