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];
}
}