iOS实现电商购物车界面示例

2020-01-18 18:12:10于丽

2.7 实现表格的代理方法


//返回单元格个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
 return infoArr.count;
}
//定制单元格内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 static NSString *identify = @"indentify";
 MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
 if (!cell)
 {
 cell = [[MyCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
 cell.delegate = self;
 }
 //调用方法,给单元格赋值
 [cell addTheValue:infoArr[indexPath.row]];
return cell;
}

//返回单元格的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
 return 120;
}

//单元格选中事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
/**
 * 判断当期是否为选中状态,如果选中状态点击则更改成未选中,如果未选中点击则更改成选中状态
 */
GoodsInfoModel *model = infoArr[indexPath.row];
if (model.selectState)
{
 model.selectState = NO;

}
else
{
 model.selectState = YES;
}
//刷新整个表格

// [_MyTableView reloadData];

//刷新当前行
[_MyTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];


[self totalPrice];

}

2.8 实现单元格加、减按钮代理
先要再ViewController.m 中导入MyCustomCellDelegate 协议
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,MyCustomCellDelegate>
然后实现代码如下:


#pragma mark -- 实现加减按钮点击代理事件

/**
* 实现加减按钮点击代理事件
*
* @param cell 当前单元格
* @param flag 按钮标识,11 为减按钮,12为加按钮
*/

-(void)btnClick:(UITableViewCell *)cell andFlag:(int)flag
{
 NSIndexPath *index = [_MyTableView indexPathForCell:cell];

switch (flag) {
 case 11:
 {
 //做减法
 //先获取到当期行数据源内容,改变数据源内容,刷新表格
 GoodsInfoModel *model = infoArr[index.row];
 if (model.goodsNum > 1)
 {
  model.goodsNum --;
 }
 }
 break;
 case 12:

 {
 //做加法
 GoodsInfoModel *model = infoArr[index.row];

 model.goodsNum ++;

 }

 break;

 default:

 break;

}
//刷新表格
[_MyTableView reloadData];

//计算总价
[self totalPrice];

}

2.9 全选方法的实现


/**
* 全选按钮事件
*
* @param sender 全选按钮
*/
-(void)selectBtnClick:(UIButton *)sender
{
 //判断是否选中,是改成否,否改成是,改变图片状态
 sender.tag = !sender.tag;
 if (sender.tag)
 {
 [sender setImage:[UIImage imageNamed:@"复选框-选中.png"] forState:UIControlStateNormal];

}else{
 [sender setImage:[UIImage imageNamed:@"复选框-未选中.png"] forState:UIControlStateNormal];
}
//改变单元格选中状态
for (int i=0; i<infoArr.count; i++)
{
 GoodsInfoModel *model = [infoArr objectAtIndex:i];
 model.selectState = sender.tag;

}
//计算价格
[self totalPrice];
//刷新表格
[_MyTableView reloadData];

}