兩個代理方法實現iOS購物車1-精簡版

首頁圖.png

沒有用到通知.只要兩個代理方法實現購物車

github的地址:https://github.com/zhYes/YSShoppingCar.git

效果展示:

購物車.gif

二. 簡介:

1.第三方:用到的框架SDWebImage/MJExtension,應該都很熟悉,第一個是圖片下載,第二個是字典轉模型.

2.功能: ①勾選總價計算; ②刪除功能

三. 使用:

0.拖入相關文件

#import "ViewController.h"
#import "MKShopCarController.h"
#import "MKOrderListModel.h"
#import "MJExtension.h"

1.傳遞數據

// 傳遞模型數據
- (void)shopCarClick {
    MKShopCarController * shop = [MKShopCarController new];
    shop.modelList = _nmArray;
    [self.navigationController pushViewController:shop animated:YES];
}

2.修改模型數據


修改模型key值.png

@end
@end

四. 代碼實現

  • 1
// 繼承UIViewController
@interface MKShopCarController   : UIViewController
// 設置表格
- (void)setTableList {
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    UINib * nib = [UINib nibWithNibName:@"MKShopCarCell" bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:@"shop"];
    _tableView.rowHeight = 110;
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
}

這里創建為UITableViewStylePlain樣式組頭會停住
UITableViewStyleGroup樣式組頭不會停住,這也是分組樣式與否的區別

  • 2.第一個代理方法,自定義cell中,選中按鈕的點擊事件
    并且將當前的cell的tag值傳遞回控制器中
//自定義cell中
@interface MKShopCarCell : UITableViewCell
// 自定義cell中左側選中按鈕的點擊事件
- (IBAction)fabricSelectClick:(UIButton*)sender {
    _goodsModel.isSelected = !_goodsModel.isSelected;
    fabricSelectedBtn.selected = !fabricSelectedBtn.selected;
//    NSLog(@"%zd",self.tag);
    if ([self.shopDelegate respondsToSelector:@selector(shopCellSelectedClick:)]) {
        [self.shopDelegate shopCellSelectedClick:self.tag];
    }
}
  • 3.第二個代理方法,自定義組頭中,選中按鈕的點擊事件中
    同樣將當前section中tag傳遞
//自定義組頭中
@interface MKHeaderFooterView : UITableViewHeaderFooterView
// 組頭的點擊事件
- (void)headerBtnClick: (UIButton*)HeaderBtn :(NSInteger)section{
    HeaderBtn.selected = !HeaderBtn.selected;
    if ([self.headerDelegate respondsToSelector:@selector(headerSelectedBtnClick:)]) {
        [self.headerDelegate headerSelectedBtnClick:self.tag];
    }
}
  • 4.控制器中,遵守協議,實現這兩個代理方法
<UITableViewDelegate,UITableViewDataSource,shopCarCellDelegate,headerViewDelegate>
// 注冊cell/header 或者判斷為空的時候 創建
    UINib * nib = [UINib nibWithNibName:@"MKShopCarCell" bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:@"shop"];
    • 組頭的數據方法 | 綁定tag
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    _headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MKShopCarHeader"];
    
    if (_headerView == nil) {
        
        _headerView = [[MKHeaderFooterView alloc] init];
        _headerView.headerDelegate = self;
    }
    
    MKOrderListModel*listModel = _modelList[section];
    
    _headerView.tag = section;
    _headerView.headerBtn.selected = listModel.groupSelected;
    
    return _headerView;
}

  •   -     cell的數據源方法 | 綁定tag
    
// cell顯示內容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     MKShopCarCell*shopCell = [tableView dequeueReusableCellWithIdentifier:@"shop"];
    shopCell.shopDelegate = self;
    //取出對應組的對應商品信息
    shopCell.goodsModel = ((MKOrderListModel*)_modelList[indexPath.section]).goods[indexPath.row];
    
    // 給cell做標記
    shopCell.tag = (long)indexPath.section *100 + (long)indexPath.row;
//    if (_modelList.count != self.dic.count) {
    
        NSString * cellTag = [NSString stringWithFormat:@"%zd",shopCell.tag];
        NSDictionary* _tempDic = @{
                     cellTag:indexPath
                     };
        [self.dic addEntriesFromDictionary:_tempDic];
//    }
    return shopCell;
}

這里將所有的indexpath存入一個字典里,并通過對應的tag作為key值
為保證唯一性section和row都做了處理作為key

    • 實現cell中的代理方法 | 計算選中與未選中的總價
#pragma mark - cell上的代理方法獲 | 取的價格
- (void)shopCellSelectedClick:(NSInteger)shopCellTag {
    
    //判斷組的是否選中狀態是否修改
    NSString * cellTagStr = [NSString stringWithFormat:@"%zd",shopCellTag];
    NSIndexPath *indexPath = self.dic[cellTagStr];
    MKOrderListModel * listModel = (MKOrderListModel*)_modelList[indexPath.section];
    
    //0.便利當前組cell上選中按鈕的個數
    NSInteger seletedNum =0;
    for (MKGoodsModel* goodsModel in listModel.goods) {
        if (goodsModel.isSelected) {
            seletedNum += 1;
        }
        
        // 1.當前組的cell的個數 是否等于 勾選的總數
        if (((MKOrderListModel*)_modelList[indexPath.section]).goods.count == seletedNum) {
            listModel.groupSelected = YES;
        } else {
            listModel.groupSelected = NO;
        }
        [_tableView reloadData];
    }
    
    MKGoodsModel *goodsModel = ((MKOrderListModel*)_modelList[indexPath.section]).goods[indexPath.row];
    float shop_price = goodsModel.shop_price;
    float goods_number = goodsModel.goods_number;
    if (!goodsModel.isSelected) {
        _totalNum = _totalNum - shop_price*goods_number;
    }else {
        
        _totalNum = _totalNum + shop_price*goods_number;
    }
    _hejiLabel.text = [NSString stringWithFormat:@"¥%.2f",_totalNum -1 + 1];
}

即,根據代理中的tag 取出 indexpath 再根據indexpath 取出模型中的數據
另外判斷本組中的cell都選中時候組的選中狀態也為選中!

    • 實現header中我們寫的的代理方法 | 計算選中與未選中的總價
#pragma mark - 代理方法組頭header的選中狀態
- (void)headerSelectedBtnClick:(NSInteger)section {
    //    NSLog(@"%zd",section);
    MKOrderListModel*listModel = _modelList[section];
    listModel.groupSelected = !listModel.groupSelected;
    
    // 判斷如果點擊 | header選中
    if (listModel.groupSelected) {
        
        for (MKGoodsModel* goodsModel in listModel.goods) {
            
            if (!goodsModel.isSelected) {                      //下面不是選中狀態的cell 將價格加入到總價當中
                float shop_price = goodsModel.shop_price;     //價格
                float goods_number = goodsModel.goods_number;   // 數量
                _totalNum += shop_price * goods_number;
                goodsModel.isSelected = YES;
            }
            
        }
    } else {  // 取消header選中 所有都取消
        for (MKGoodsModel* goodsModel in listModel.goods) {
            goodsModel.isSelected = NO;
            float shop_price = goodsModel.shop_price;               //價格
            float goods_number = goodsModel.goods_number;   // 數量
            _totalNum -= shop_price * goods_number;
        }
    }
//    NSLog(@"總價格為: %.2f",_totalNum);
    _hejiLabel.text = [NSString stringWithFormat:@"¥%.2f",_totalNum - 1 + 1];
    [_tableView reloadData];
}

邏輯分析: 組頭點擊選中 : 則遍歷本組cell 未選中狀態的cell計算價格加入到總價更并改cell選中狀態
組頭點擊未選中 : 遍歷本組中cell 的價格 從總價中減去并更改cell的選中狀態
最后reloadData

    • 刪除方法 | 根據方法中自帶的indexpath從數據中刪除跟新即可
//左拉抽屜(刪除和修改按鈕)
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 添加一個刪除按鈕
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"刪除"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        MKOrderListModel*listModel = _modelList[indexPath.section];
        
        NSMutableArray*goodsModel = (NSMutableArray*)listModel.goods;
        
        /// 如果刪除的是帶勾選的則計算一次數值
        MKGoodsModel*goodModel = (MKGoodsModel*)goodsModel[indexPath.row];
        if (goodModel.isSelected) {
            float shop_price = goodModel.shop_price;               //價格
            float goods_number = goodModel.goods_number;   // 數量
            _totalNum -= shop_price * goods_number;
            _hejiLabel.text = [NSString stringWithFormat:@"%.2f",_totalNum];
        }
        
        [goodsModel  removeObjectAtIndex:indexPath.row];    // 刪除操作放到最后
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        if (goodsModel.count == 0) {
            NSMutableArray *temp = [NSMutableArray arrayWithArray:_modelList];
            [temp removeObjectAtIndex:indexPath.section];
            _modelList = temp;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [tableView reloadData];
        });
    }];
    
    // 修改資料按鈕
    UITableViewRowAction *editRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"修改"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
    }];
    
    editRowAction.backgroundColor = [UIColor blueColor];
    // 將設置好的按鈕放到數組中返回
    return @[deleteRowAction, editRowAction];
}

注意點 : ①可能遇到刪除報錯的情況,需要條件到一個臨時的可變數組中做刪除操作 再把刪除后的數組回傳
②判斷刪除cell中的選中,如果選中狀態則在總價中減去此價格即可
③刪除操作這里需要增加接口后臺數據做刪除

純手打,如果有用希望多多支持!~

兩個代理方法實現iOS購物車2-完整版

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,983評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,772評論 3 422
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,947評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,201評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,960評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,350評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,406評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,549評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,104評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,914評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,089評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,647評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,340評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,753評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,007評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,834評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,106評論 2 375

推薦閱讀更多精彩內容