您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

高還原電商購物車實作拆解:Auto Layout 雙層 Cell 自適應與全互動邏輯

編輯:iOS 開發綜合

剛做完一版購物車,本來是照著淘寶的邏輯做的,結果換了產品經理,人家偏好京東那種風格,一句「換個風格」就全部重來。既然需求來了,那就照著改,順便把過程整理成一份 Demo 分享出來。

整個主介面全靠 Auto Layout 撐起來,光主控制器就接近 800 行,全部加起來相當可觀。效果基本都實現了,先看圖。

再來一組:

功能盤點

  1. 為 UIKit 控件擴充 Badge 能力(需要時可自行從原始碼中摘取)。
  2. 加入購物車時的「凹陷」過場動畫。
  3. 購物車純 Auto Layout 實作雙層 Cell 高度自適應。
  4. 動態計算價格、多選或單選刪除、編輯狀態切換 Cell、簡單富文本等基礎邏輯。
  5. 底部加入相關商品推薦(本質上是給 tableFooterView 塞一個 CollectionView)。
  6. 圖片瀏覽元件(JTSImageViewController)。
  7. 為了不讓看的人無聊,選了幾張妹子圖。

一、進入購物車前的凹陷過場

- (void)show:(UITapGestureRecognizer *)tap {
    if (!self.chooseVC) {
        self.chooseVC = [[ChooseGoodsPropertyViewController alloc] init];
    }
    self.chooseVC.enterType = FirstEnterType;
    __weak typeof(self) weakSelf = self;
    self.chooseVC.block = ^{
        NSLog(@"點擊回調去購物車");
        // 這裡一定要移除,否則控制器階層會亂掉。
        // 這個效果其實是 addChildVC 來的,最終展示在 Window 上,必須收尾。
        [weakSelf.chooseVC.view removeFromSuperview];
        [weakSelf.chooseVC removeFromParentViewController];
        weakSelf.chooseVC.view = nil;
        weakSelf.chooseVC = nil;

        MKJShoppingCartViewController *shop = [MKJShoppingCartViewController new];
        [weakSelf.navigationController pushViewController:shop animated:YES];
    };
    self.chooseVC.price = 256.0f;
    [self.navigationController presentSemiViewController:self.chooseVC withOptions:@{
        KNSemiModalOptionKeys.pushParentBack : @(YES),
        KNSemiModalOptionKeys.animationDuration : @(0.6),
        KNSemiModalOptionKeys.shadowOpacity : @(0.3),
        KNSemiModalOptionKeys.backgroundView : [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background_01"]]
    }];
}

要注意的是它的視圖階層關係。如果你要 push 到下一個介面,務必把子控制器與它的 view 都 remove 掉,最好直接把指標置為 nil,就像上面這樣。否則視圖階層會殘留,介面顯示就會出問題。

二、Auto Layout 實作雙層 Cell

先看視圖樹結構:

contentView
├── NormalView(正常狀態下的控件)
│  ├── chooseButton
│  └── ProductImageView
└── EditBackView(編輯狀態下的控件)

這個 Cell 裡面有二十多個控件,全部用約束固定好,再搭配 FD 系列工具,一行程式碼就能實現高度自適應,還能同時支援編輯與非編輯兩種狀態。

這一套下來省了好幾百行程式碼。

// 高度計算
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BuyerInfo *buyer = self.buyerLists[indexPath.section];
    if (buyer.buyerIsEditing) {
        return 100;
    } else {
        CGFloat actualHeight = [tableView fd_heightForCellWithIdentifier:shoppongID
                                                        cacheByIndexPath:indexPath
                                                          configuration:^(ShoppingCartCell *cell) {
            [self configCell:cell indexPath:indexPath];
        }];
        return actualHeight >= 100 ? actualHeight : 100;
    }
}

再搭配一套 delegate,Cell 的互動就完整了:

@protocol ShoppingCartCellDelegate <NSObject>
// 點擊單個商品選擇按鈕回調
- (void)productSelected:(ShoppingCartCell *)cell isSelected:(BOOL)choosed;
// 點擊買手選擇按鈕回調
- (void)buyerSelected:(NSInteger)sectionIndex;
// 點擊買手編輯回調
- (void)buyerEditingSelected:(NSInteger)sectionIdx;
// 點擊垃圾桶刪除
- (void)productGarbageClick:(ShoppingCartCell *)cell;
// 點擊編輯規格下拉回調
- (void)clickEditingDetailInfo:(ShoppingCartCell *)cell;
// 商品數量增加或減少回調
- (void)plusOrMinusCount:(ShoppingCartCell *)cell tag:(NSInteger)tag;
// 點擊圖片跳轉展示
- (void)clickProductIMG:(ShoppingCartCell *)cell;
@end

@interface ShoppingCartCell : UITableViewCell
@property (nonatomic, assign) id<ShoppingCartCellDelegate> delegate;
@end

三、互動邏輯實作

這部分思路是統一的:在商品 model 與買手 model 上各加一個 BOOL 欄位作為開關,然後在載入 cell 時依狀態做判斷。

1. 計算總價

只需要依商品的選取狀態累加即可:

#pragma mark - 計算選出商品的總價
- (CGFloat)countTotalPrice {
    CGFloat totalPrice = 0.0;
    for (BuyerInfo *buyer in self.buyerLists) {
        if (buyer.buyerIsChoosed) {
            // 買手整體被選中,累加他底下所有商品
            for (ProductInfo *product in buyer.prod_list) {
                totalPrice += product.order_price * product.count;
            }
        } else {
            // 否則只累加被單獨勾選的商品
            for (ProductInfo *product in buyer.prod_list) {
                if (product.productIsChoosed) {
                    totalPrice += product.order_price * product.count;
                }
            }
        }
    }
    return totalPrice;
}

2. 多選刪除

這裡有個必踩的坑:批次刪除時絕對不能在 for 迴圈裡一個一個刪,必須先收集到暫存陣列,再統一刪除,否則索引會越界直接崩潰。

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 單個刪除
    if (alertView.tag == 101) {
        if (buttonIndex == 1) {
            NSIndexPath *indexpath = [self.tableView indexPathForCell:self.tempCellArray.firstObject];
            BuyerInfo *buyer = self.buyerLists[indexpath.section];
            ProductInfo *product = buyer.prod_list[indexpath.row];
            if (buyer.prod_list.count == 1) {
                // 該買手下只剩一個商品,連買手一起移除
                [self.buyerLists removeObject:buyer];
            } else {
                [buyer.prod_list removeObject:product];
            }
            [self updateInfomation];
        }
    } else if (alertView.tag == 102) { // 多個或單個
        if (buttonIndex == 1) {
            NSMutableArray *buyerTempArr = [[NSMutableArray alloc] init];
            for (BuyerInfo *buyer in self.buyerLists) {
                if (buyer.buyerIsChoosed) {
                    // 買手整體被選中,直接收集起來
                    [buyerTempArr addObject:buyer];
                } else {
                    NSMutableArray *productTempArr = [[NSMutableArray alloc] init];
                    for (ProductInfo *product in buyer.prod_list) {
                        if (product.productIsChoosed) {
                            // 先收集,不要邊遍歷邊刪
                            [productTempArr addObject:product];
                        }
                    }
                    if (![[MKJRequestHelper shareRequestHelper] isEmptyArray:productTempArr]) {
                        [buyer.prod_list removeObjectsInArray:productTempArr];
                    }
                }
            }
            [self.buyerLists removeObjectsInArray:buyerTempArr];
            [self updateInfomation];
        }
    }
}

3. 狀態同步更新

任何刪除、選取、增減數量之後,價格、數量、全選狀態都要一併刷新,這一步最容易漏。

#pragma mark - 刪除之後的一系列更新操作
- (void)updateInfomation {
    // 商品變動會反過來影響買手的選取狀態
    for (BuyerInfo *buyer in self.buyerLists) {
        NSInteger count = 0;
        for (ProductInfo *product in buyer.prod_list) {
            if (product.productIsChoosed) {
                count++;
            }
        }
        if (count == buyer.prod_list.count) {
            buyer.buyerIsChoosed = YES;
        }
    }
    // 再影響全選按鈕
    self.allSelectedButton.selected = [self isAllProcductChoosed];
    // 總價
    self.totalPriceLabel.text = [NSString stringWithFormat:@"合計¥%.2f", [self countTotalPrice]];
    // 結算按鈕
    [self.accountButton setTitle:[NSString stringWithFormat:@"結算(%ld)", [self countTotalSelectedNumber]]
                        forState:UIControlStateNormal];
    [self.tableView reloadData];
    // 如果全部刪空了
    if ([[MKJRequestHelper shareRequestHelper] isEmptyArray:self.buyerLists]) {
        [self clickAllEdit:self.rightButton];
        self.rightButton.enabled = NO;
    }
}

四、底部推薦區

給 tableFooterView 塞一個 CollectionView,後續要加各種推薦內容都方便擴充。關鍵在於:先拿到 layout 的內容尺寸,再決定 footer 高度,最後才賦值,這樣才不會出現顯示抖動。

// 請求相關商品資料
[[MKJRequestHelper shareRequestHelper] requestMoreRecommandInfo:^(id obj, NSError *err) {
    [weakSelf.relatedProducts removeAllObjects];
    weakSelf.relatedProducts = [[NSMutableArray alloc] initWithArray:(NSArray *)obj];
    [weakSelf.collectionView reloadData];
    // 依刷新後的資料取得 collectionViewContentSize 的高度
    weakSelf.underFooterView.frame = CGRectMake(0, 0,
        [UIScreen mainScreen].bounds.size.width,
        weakSelf.collectionView.collectionViewLayout.collectionViewContentSize.height);
    // 最後再賦值,避免顯示不順暢
    weakSelf.tableView.tableFooterView = weakSelf.underFooterView;
}];

五、圖片瀏覽

#pragma mark - 點擊圖片展示
- (void)clickProductIMG:(ShoppingCartCell *)cell {
    NSIndexPath *indexpath = [self.tableView indexPathForCell:cell];
    BuyerInfo *buyer = self.buyerLists[indexpath.section];
    ProductInfo *product = buyer.prod_list[indexpath.row];

    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    imageInfo.imageURL = [NSURL URLWithString:product.image];

    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
        initWithImageInfo:imageInfo
                     mode:JTSImageViewControllerMode_Image
          backgroundStyle:JTSImageViewControllerBackgroundOption_Scaled];
    [imageViewer showFromViewController:self
                           transition:JTSImageViewControllerTransition_FromOffscreen];
}

最後:別忘了檢查記憶體洩漏

- (void)dealloc {
    NSLog(@"%s____dealloc", object_getClassName(self));
}

能正常印出這行,大致就沒問題了。

這個 Demo 用的是本地假資料,真正上線還要接後端介面。整體寫下來,程式碼量其實不是重點,真正的複雜度全在狀態判斷與同步上。可能有不足之處,畢竟只是 Demo,拋磚引玉,覺得有幫助的話不妨下載研究看看。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved