iOS 购物车的全选,单选的实现方法

本文介绍了一种利用字典数据结构实现类似淘宝购物车全选功能的方法。通过定义数组存储商品数据,并使用字典存储已选商品,利用字典key不重复特性确保唯一性。文章提供了关键代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类似淘宝的购物车类型

实现方法有千万种,我使用了字典数据key不能重复的特性,当然集合也具备这个特性,只要具备这个特性的都可以使用这种思路实现购物车的全选,

我定义了一个数组listArray 存储所有的数据类型,和一个selectDict选中的商品字典类型

selectDict存储数据类型大概是这样


将选中cell的indexPath设为字典的key,以为key不能重复,因此不需要担心会有重复的可能。

只要在- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section方法中对字典的

[dict allValues].count == 商品的数量  就可以知道是否是全部选中。


#下面是部分实现源码

//判断是否是全部选中

- (BOOL)JudgementSelectAll:(NSIndexPath *)indexPath{

    NSDictionary *dict =EncodeDicFromDic(self.selectDict, [NSStringstringWithFormat:@"%ld",indexPath.section]);

    NSInteger tag =1000 + indexPath.section;

//     MyCartHeadView *view = [self.view viewWithTag:tag];

    if ([dictallValues].count ==EncodeArrayFromDic(self.listArray[indexPath.section],@"cartList").count) {

//        view.selectedBtn.selected = YES;

        returnYES;

    }else{

//        view.selectedBtn.selected = NO;

        returnNO;

    }

}

//sectionView

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section <self.listArray.count) {

        MyCartHeadView *view = [[[NSBundlemainBundle] loadNibNamed:@"MyCartHeadView"owner:niloptions:nil]lastObject];

        view.section = section;

        __blocktypeof(self)weakSelf =self;

        view.selectBlock = ^(NSInteger section,BOOL select){

            if (select) {

                NSMutableDictionary *dict =EncodeMutableDicFromDic(self.selectDict, [NSStringstringWithFormat:@"%ld",section]);

                if (!dict) {

                    dict = [NSMutableDictionarydictionary];

                }

                for (int i =0; i < EncodeArrayFromDic(weakSelf.listArray[section],@"cartList").count; i++) {

                    [dict setValue:@"1"forKey:[NSStringstringWithFormat:@"%d",i]];

                }

                [weakSelf.selectDictsetValue:dict forKey:[NSStringstringWithFormat:@"%ld",section]];

            }else{

                [weakSelf.selectDictsetValue:nilforKey:[NSStringstringWithFormat:@"%ld",section]];

            }

            [weakSelf.tableViewreloadData];

        };

        view.selectedBtn.selected = [selfJudgementSelectAll:[NSIndexPathindexPathForRow:0inSection:section]];

        return view;

    }

    returnnil;

}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值