购物车实现 <Block实现回调>

效果图如下:

具体代码实现如下:

Model:

#import <Foundation/Foundation.h>

@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 <UIKit/UIKit.h>
@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(35, 10, 35, 10)];
    _selectedButton.frame = CGRectMake(0, 0, 40, 90);
    _selectedButton.tag = 101;
    [_selectedButton addTarget:self action:@selector(isselectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_selectedButton];
    
    _GoodsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_selectedButton.frame.origin.x + 40, 10, 70, 70)];
    _GoodsImageView.layer.cornerRadius = 10;
    [self.contentView addSubview:_GoodsImageView];
    
    _goodsNameLable = [[UILabel alloc]initWithFrame:CGRectMake(_GoodsImageView.frame.origin.x + 80, 10, [UIScreen mainScreen].bounds.size.width - 50 - _GoodsImageView.frame.origin.x - 70 - 10, 30)];
    _goodsNameLable.textAlignment = NSTextAlignmentLeft;
    _goodsNameLable.font = [UIFont systemFontOfSize:14];
    _goodsNameLable.textColor = [UIColor blackColor];
    _goodsNameLable.numberOfLines = 0;
    [self.contentView addSubview:_goodsNameLable];
    
    _goodsPriceLable = [[UILabel alloc]initWithFrame:CGRectMake(_goodsNameLable.frame.origin.x, 55,[UIScreen mainScreen].bounds.size.width - 110 - _GoodsImageView.frame.origin.x - 70 - 10, 30)];
    _goodsPriceLable.textAlignment = NSTextAlignmentLeft;
    _goodsPriceLable.textColor = [UIColor redColor];
    _goodsPriceLable.font = [UIFont systemFontOfSize:13];
    _goodsPriceLable.numberOfLines = 0;
    [self.contentView addSubview:_goodsPriceLable];
    
    _deletButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _deletButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 40, 10, 30, 20);
    [_deletButton setTitle:@"删除" forState:UIControlStateNormal];
    [_deletButton setTitle:@"删除" forState:UIControlStateHighlighted];
    [_deletButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _deletButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_deletButton addTarget:self action:@selector(deletButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _deletButton.tag = 102;
    [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(15, 10, 15, 5)];
    _subtractButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 110, 40, 35, 50);
    _subtractButton.titleLabel.font = [UIFont systemFontOfSize:14];
    _subtractButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_subtractButton addTarget:self action:@selector(subStractButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _subtractButton.tag = 105;
    [self.contentView addSubview:_subtractButton];
    
    _goodsCountTextfield = [[UITextField alloc]initWithFrame:CGRectMake(_subtractButton.frame.origin.x + 37, _subtractButton.frame.origin.y + 15, 36, 20)];
    _goodsCountTextfield.borderStyle = 3;
    _goodsCountTextfield.textColor = [UIColor blackColor];
    _goodsCountTextfield.textAlignment = NSTextAlignmentCenter;
    _goodsCountTextfield.font = [UIFont systemFontOfSize:14];
    _goodsCountTextfield.enabled = NO;
    [self.contentView addSubview:_goodsCountTextfield];
    
    _addButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _addButton.frame = CGRectMake(_goodsCountTextfield.frame.origin.x + 36 + 2, _goodsCountTextfield.frame.origin.y - 15, 35, 50);
    [_addButton setImageEdgeInsets:UIEdgeInsetsMake(15, 5, 15, 10)];
    [_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:14];
    _addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_addButton addTarget:self action:@selector(addButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _addButton.tag = 106;
    [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 < 1) {
        _goodsCountTextfield.text = @"1";
    }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 ()<UITableViewDelegate,UITableViewDataSource>
{
    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(0, 0, ScreenWidth, ScreenHeight - 44) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 90;
    [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(0, ScreenHeight - 44, ScreenWidth, 44)];
    [self.view addSubview:bottomView];
    
    //全选按钮
    allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    allButton.frame = CGRectMake(10, 10, 24, 24);
    [allButton setImage:[UIImage imageNamed:@"radiobuttons_normal"] forState:UIControlStateNormal];
    [allButton setImage:[UIImage imageNamed:@"radiobuttons_pressed"] forState:UIControlStateSelected];
    allButton.titleLabel.font = [UIFont systemFontOfSize:14];
    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 + 28, allButton.frame.origin.y - 3, 30, 30)];
    quanxuanLable.text = @"全选";
    quanxuanLable.font = [UIFont systemFontOfSize:14];
    quanxuanLable.textAlignment = NSTextAlignmentLeft;
    [bottomView addSubview:quanxuanLable];
    
    moneyLable = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2.0 - 80, allButton.frame.origin.y, 160, 25)];
    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:14];
    moneyLable.textAlignment = NSTextAlignmentCenter;
    [bottomView addSubview:moneyLable];
    
    //结算按钮
    balanceButton = [UIButton buttonWithType:UIButtonTypeSystem];
    balanceButton.frame = CGRectMake(ScreenWidth - 80, 10, 70, 40);
    balanceButton.backgroundColor = [UIColor redColor];
    [balanceButton setTitle:@"结算" forState:UIControlStateNormal];
    [balanceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    balanceButton.titleLabel.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:16];
    //字体祖后面加-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 - 120, self.view.frame.size.height/2.0 - 130, 240, 260)];
    _backGrundImageView.image = [UIImage imageNamed:@"购物车空"];
    _backGrundImageView.hidden = YES;
    [bottomView addSubview:_backGrundImageView];

}

#pragma mark - loadData

- (void)loadData{
    
    //设置购物车的模拟数据
    for (int i = 0; i < 10; 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:@"1" 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 == 99) {
            NSLog(@"不能再多啦!!!");
            [self showAlertView:@"不能再多啦!!!"];
            [weakSelf sumOfAllPrice];
            [weakSelf.tableView reloadData];
        }
        // 注意是 >= 1
        if (model.goodsCount >= 1) {
            model.goodsCount++;
            [weakSelf sumOfAllPrice];
            [weakSelf.tableView reloadData];
        }
    };
    cell.subTractBlock = ^ (NSIndexPath *indexPath){
        
        // 取得model
        ShopCarModel *model = weakSelf.dataArray[indexPath.row];
        if (model.goodsCount == 1) {
            NSLog(@"不能再少啦!!!");
            [self showAlertView:@"不能再少啦!!!"];
            return ;  // 让其不能再往下执行了
        }
        if (model.goodsCount < 99) {
           model.goodsCount = model.goodsCount - 1;
            [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 = 0; 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 == 2 && [[array objectAtIndex:1]floatValue] < 0.00000001) {
        message = @"请先选择商品哟!!!";
        carStr = @"请先选择商品哟!!!";
    }else{
        
        message = @"去结算";
        carStr = [NSString stringWithFormat:@"总计:%d元",[[array objectAtIndex:1] intValue]];
    }
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:carStr message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}

- (void)sumOfAllPrice{
    
    for (NSInteger i = 0; 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...嘿嘿嘿!!!>

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

原文地址:https://www.cnblogs.com/pengsi/p/5782986.html