iOS开发——做购物车,看我就够了

大家可以先看一下最终的效果:

购物车最终的效果

在这里,先讲一下购物车的需求,就是普通的购物车,每种商品都有对应商品的折扣价,其中一种商品满5件时,购物车对应的商品会显示折扣价,每种商品都有商品小计。在这里,为了方便演示,我就建了一个商品的model,然后通过plist文件建了一个简单的数据源吧,通过解析plist文件来充当我们首页的商品数据,点击加入购物车会将对应的商品数据通过FMDB存到本地,而在购物车页面,是通过查询本地数据库来获取购物车数据的,如果数据库中没有数据,就会显示一个空的页面,通过点击一个去首页的按钮跳到首页,如果有数据,直接获取数据,通过tableView展示购物车信息。

难点:
1、各种按钮(cell上的选中按钮和全选按钮)的点击配合。
2、删除的时候,删除的商品数据是选中的还是没选中的,要分开判断。
3、点击结算按钮,返回之后商品的选中按钮状态和全选按钮的状态。

技巧:
在开发中,我们经常用到在控制器外面封装一个UIView,如今,我们都经常使用xib或者storyBoard开发,但是我们要想封装UIView,不能直接给UIView创建xib文件,所以我们需要先把UIView创建了,之后再创建一个带view的可视化文件,以我们创建view的类名开头,.xib结尾,然后关联在一起(或者不带view的,然后拖一个view进去),这样我们就可以像平时一样在xib中拖各种控件了。需要注意的是,第一步(重要):


1、此处设置我们需要关联的view类

第二步(同样重要):在.h中写一个类方法,供外界调用,然后在.m中实现代码关联。


2、代码关联

好了,说了这么多,也算一个小技巧吧,这个小购物车中,总计那一条view我是用这个方法做的,不值一提,最后还是根据大家自己平时的习惯来封装view。。。。

购物车中用到了FMDB,所以我又对它封装了一下,更加简单,需要用的时候,直接调用就行了 😄😄😄

先说一下思路:查询本地数据库获得的是初始数据源,在增加修改,都需要对本地数据库进行修改,然后界面同步更新;删除的时候,先操作数据,最后删除UI;别的就是按钮之间的关系了,如果想看demo源码,下载链接:https://github.com/fashion98/FSCartDemo

下面奉上购物车对应控制器中的代码:关键代码已附上注释,有什么疑问可以下方评论或者直接简信我😄

@interface FSCartVC ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UIImageView *noGoodsImgView;       // 当购物车没有商品的时候的图片
@property (strong, nonatomic) UIButton *goHomeViewButton;        // 当购物车没有商品的时候跳到首页的按钮

@property (strong, nonatomic) UITableView *shopcartTableView;    // 购物车的tableView
@property (strong, nonatomic) NSMutableArray *shopcartGoodsArray;// 购物车数据源数组
@property (strong, nonatomic) NSMutableArray *resultArray;       // 选中商品的model数组

@property (strong, nonatomic) FSSumView *sumView;                // 总计的view

@property (assign, nonatomic) BOOL isSelectAll;                  // 是否全选

@end

#define kScreenWidth   [UIScreen mainScreen].bounds.size.width
#define kScreenHeight  [UIScreen mainScreen].bounds.size.height

static NSString *cellID = @"FSShopCartCell";
@implementation FSCartVC

- (void)viewWillAppear:(BOOL)animated
{
    
    self.resultArray = [NSMutableArray array];
    [self.resultArray removeAllObjects];
    self.shopcartGoodsArray = [NSMutableArray array];
    
    NSString *searchAllSQL = [NSString stringWithFormat:@"select * from goods"];
    
    [FSFMDB findSQLWithPathComponent:@"goods.sqlite"];
    
    [FSFMDB searchAllDataWithSQL:searchAllSQL andResultBlock:^(BOOL success, NSMutableArray *goodList) {
        
        if (success)
        {
            self.shopcartGoodsArray = goodList;
        }
        NSLog(@"%@", self.shopcartGoodsArray);
    }];
    
    if (self.shopcartGoodsArray.count>0)
    {
        [self initView];
    }
    else
    {
        [self initNoGoodsView];
    }
    
    // 每次界面将要显示的时候,将全选状态置为NO
    self.isSelectAll = NO;
    
    [self.shopcartTableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"购物车";

    self.view.backgroundColor = [UIColor colorWithRed:242/250.0 green:243/250.0 blue:240/250.0 alpha:1];
}


#pragma mark ____ 您的购物车空... ____
- (void)initNoGoodsView
{
    self.noGoodsImgView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth-90)/2, 64, 90, 90*1.28)];
    self.noGoodsImgView.image = [UIImage imageNamed:@"noGoodsBG"];
    [self.view addSubview:self.noGoodsImgView];
    
    self.goHomeViewButton = [[UIButton alloc] initWithFrame:CGRectMake((kScreenWidth-90)/2, CGRectGetMaxY(self.noGoodsImgView.frame)+10, 90, 20)];
    self.goHomeViewButton.backgroundColor = [UIColor orangeColor];
    [self.goHomeViewButton setTitle:@"去首页逛逛" forState:(UIControlStateNormal)];
    self.goHomeViewButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.goHomeViewButton addTarget:self action:@selector(goHomeViewAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.goHomeViewButton];
}

- (void)goHomeViewAction:(UIButton *)button
{
    self.tabBarController.selectedIndex = 0;
}


- (void)initView
{
    self.shopcartTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-49-50) style:(UITableViewStylePlain)];
    self.shopcartTableView.backgroundColor = [UIColor colorWithRed:242/250.0 green:243/250.0 blue:240/250.0 alpha:1];
    self.shopcartTableView.delegate = self;
    self.shopcartTableView.dataSource = self;
    [self.view addSubview:self.shopcartTableView];
    
    [self.shopcartTableView registerNib:[UINib nibWithNibName:@"FSShopCartCell" bundle:nil] forCellReuseIdentifier:cellID];
    self.shopcartTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.sumView = [FSSumView initView];
    self.sumView.frame = CGRectMake(0, kScreenHeight - 49 - 64 - 50, kScreenWidth, 50);
    [self.sumView.selectAllButton addTarget:self action:@selector(selectAllAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.sumView.payButton addTarget:self action:@selector(jiesuanAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.sumView];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.shopcartGoodsArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FSShopCartCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.isSelected = self.isSelectAll;// 绘制cell的时候先将是否全选的状态赋给cell
    
    if ([self.resultArray containsObject:self.shopcartGoodsArray[indexPath.section]]) {
        
        cell.isSelected = YES; // 如果结算数组中包含当前cell的model,就要将当前cell的选中状态置为YES
    }
    
    // cell中选中按钮的点击回调
    cell.cellBlock = ^(BOOL isSelect){
        
        if (isSelect)
        {
            [self.resultArray addObject:self.shopcartGoodsArray[indexPath.section]];
        }
        else
        {
            [self.resultArray removeObject:self.shopcartGoodsArray[indexPath.section]];
        }
        
        if (self.resultArray.count == self.shopcartGoodsArray.count)
        {
            self.sumView.selectAllButton.selected = YES;
        }
        else
        {
            self.sumView.selectAllButton.selected = NO;
        }
        
        [self calculateTheTotalPrice];
        
    };
    
    // cell中-号点击的回调
    cell.cutNumBlock = ^(UILabel *numLabel){
        
        int num = numLabel.text.intValue;
        
        FSGoods *goods = self.shopcartGoodsArray[indexPath.section];
        
        if (num > 1) {
            
            num--;
            numLabel.text = [NSString stringWithFormat:@"%zd", num];
            
            [self cutOneGoods:goods];
        }
        
        goods.goodsNum = num;
        
        [self.shopcartGoodsArray replaceObjectAtIndex:indexPath.section withObject:goods];
        if ([self.resultArray containsObject:goods])
        {
            [self.resultArray removeObject:goods];
            [self.resultArray addObject:goods];
            [self calculateTheTotalPrice];
        }
        
        [self.shopcartTableView reloadData];
        
    };
    
    // cell中+号点击的回调
    cell.addNumBlock = ^(UILabel *numLabel){
        
        int num = numLabel.text.intValue;
        
        num++;
        numLabel.text = [NSString stringWithFormat:@"%zd", num];
        
        
        FSGoods *goods = [self.shopcartGoodsArray objectAtIndex:indexPath.section];
        goods.goodsNum = num;
        
        [self addOneGoods:goods];
        
        [self.shopcartGoodsArray replaceObjectAtIndex:indexPath.section withObject:goods];
        if ([self.resultArray containsObject:goods])
        {
            [self.resultArray removeObject:goods];
            [self.resultArray addObject:goods];
            [self calculateTheTotalPrice];
        }
        
        [self.shopcartTableView reloadData];
    };
    
    // cell中删除按钮的回调
    cell.deleteBlock = ^(FSGoods *good){
    
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要删除该商品?删除后无法恢复!" preferredStyle:1];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            // 通过FMDB删除本地数据库对应的商品
            [FSFMDB findSQLWithPathComponent:@"goods.sqlite"];
            
            NSString *sql = [NSString stringWithFormat:@"DELETE FROM goods WHERE goodsId = '%@'", good.goodsId];
            [FSFMDB deleteWithSQL:sql andResultBlock:^(BOOL result) {
                
                if (result) {
                    
                    NSLog(@"删除成功!");
                }
            }];
            

            // 需要先判断要删除的model,结算数组里是否包含
            // 1、如果包含,结算数组也需要删除对应的model,否则会影响全选按钮的选中状态
            // 2、如果不包含,在删除数据源数组对应的model之后,需要判断结算数组和数据源数组的个数,否则同样会影响全选按钮的选中状态(eg:如果购物车中有三个model数据,选中两个model,如果删除一个未选中的model,此时全选按钮选中状态应该置为YES)
            if ([self.resultArray containsObject:self.shopcartGoodsArray[indexPath.section]]) {
                
                [self.resultArray removeObject:self.shopcartGoodsArray[indexPath.section]];
            }
            
            // 删除数据源
            [self.shopcartGoodsArray removeObjectAtIndex:indexPath.section];
            
            // 删除UI
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:(UITableViewRowAnimationFade)];
            
            
            if (self.shopcartGoodsArray.count == 0) {
                
                [self.sumView removeFromSuperview];
                [self initNoGoodsView];
            }
            
            // 判断数据源数组的个数和结算数组的个数是否相等
            if (self.resultArray.count == self.shopcartGoodsArray.count) {
                
                self.sumView.selectAllButton.selected = YES;
            }
            
            
            [self.shopcartTableView reloadData];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:okAction];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    };
    
    
    
    cell.model = self.shopcartGoodsArray[indexPath.section];
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 145;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 10;
}


// UITableView设置分区头跟随UITableView滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 10; //根据实际情况设置
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

#pragma mark ____ 数据库中相应商品数量减1 ____
- (void)cutOneGoods:(FSGoods *)model
{
    [FSFMDB findSQLWithPathComponent:@"goods.sqlite"];
    
    NSString *searchOneSQL = [NSString stringWithFormat:@"select * from goods where goodsId = '%@'", model.goodsId];
    
    [FSFMDB searchOneDataWithSQL:searchOneSQL andResultBlock:^(BOOL result, NSDictionary *dict) {
        
        if (result)
        {
            int num = [[dict objectForKey:@"goodsNum"] intValue];
            num = num - 1;
            
            [FSFMDB updateWithSQL:[NSString stringWithFormat:@"update goods set goodsNum = '%d' where goodsId = '%@'", num, model.goodsId] andResultBlocck:^(BOOL result) {
                
                if (result)
                {
                    NSLog(@"数据库里对应数据减1");
                }
                
            }];
        }
    }];
}

#pragma mark ____ 数据库中相应商品数量加1 ____
- (void)addOneGoods:(FSGoods *)model
{
    [FSFMDB findSQLWithPathComponent:@"goods.sqlite"];
    
    NSString *searchOneSQL = [NSString stringWithFormat:@"select * from goods where goodsId = '%@'", model.goodsId];
    
    [FSFMDB searchOneDataWithSQL:searchOneSQL andResultBlock:^(BOOL result, NSDictionary *dict) {
        
        if (result)
        {
            int num = [[dict objectForKey:@"goodsNum"] intValue];
            num = num + 1;
            
            [FSFMDB updateWithSQL:[NSString stringWithFormat:@"update goods set goodsNum = '%d' where goodsId = '%@'", num, model.goodsId] andResultBlocck:^(BOOL result) {
                
                if (result)
                {
                    NSLog(@"数据库里对应数据加1");
                }
                
            }];
        }
    }];
}

#pragma mark ____ 全选按钮 ____
- (void)selectAllAction:(UIButton *)button
{
    [self.resultArray removeAllObjects];
    
    button.selected = !button.selected;
    
    self.isSelectAll = button.selected;
    
    if (self.isSelectAll)
    {
        
        for (FSGoods *good in self.shopcartGoodsArray) {
            
            [self.resultArray addObject:good];
        }
        
    }else
    {
        
        [self.resultArray removeAllObjects];
    }
    
    [self calculateTheTotalPrice];
    
    [self.shopcartTableView reloadData];
}

#pragma mark ____ 计算总共价格 ____
- (void)calculateTheTotalPrice
{
    double totalPrice = 0.00;
    
    for (FSGoods *model in self.resultArray)
    {
        double a = 0.00;
        
        if (model.goodsNum < 5)
        {
            a = model.goodsNum * [model.goodsPrice doubleValue];
        }
        else
        {
            a = model.goodsNum * [model.goodsPrice doubleValue] * 0.8;// 折扣价,为了简单,我就打了8折
        }
        
        totalPrice = totalPrice + a;
    }
    
    self.sumView.priceLabel.text = [NSString stringWithFormat:@"¥%.2f", totalPrice];
}

#pragma mark ____ 结算按钮 ____
- (void)jiesuanAction
{
    if (self.resultArray.count == 0)
    {
        NSLog(@"不能结算");
    }
    else
    {
        FSOrderDetailVC *detailVC = [FSOrderDetailVC new];
        detailVC.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容