iOS-商品详情规格选择

前言:各大电商平台都有此类页面,在你选择要购买的商品时候,除了默认的商品规格外,你可以自由选择可供选择的规格,有的商品有多中规格供选择,今天分享的是当前项目中使用的一种方法,仅供参考,不足之处,欢迎指出。

先看效果图
image.png

看到这种多选的规格,第一反应就是collectionview,这个时候关键问题就出来了,规格的内容长度并不是一样的,但是系统默认的cell的宽度却只能设置成一样的,这个时候大家都知道接下来我要说的了,自定义CollectionviewFlowLayout,是的。

@protocol LeeIrregularCollectionViewFlowLayoutDelegate <NSObject>

@required

// cell size
- (CGSize)LeeIrregularCollectionViewFlowLayout:(UICollectionViewLayout *)layout itemSizeForIndexPath:(NSIndexPath *)indexPath;

@optional

// headerview size
- (CGSize)LeeIrregularCollectionViewFlowLayout:(UICollectionViewLayout *)layout headerViewSizeForIndexPath:(NSIndexPath *)indexPath;

// footerview size
- (CGSize)LeeIrregularCollectionViewFlowLayout:(UICollectionViewLayout *)layout FooterViewSizeForIndexPath:(NSIndexPath *)indexPath;

// 横向间距
- (CGFloat)LeeIrregularCollectionViewFlowLayout:(UICollectionViewLayout*)layout itemMinimumLineSpacingForIndexPath:(NSIndexPath *)indexPath;

// 竖向间距
- (CGFloat)LeeIrregularCollectionViewFlowLayout:(UICollectionViewLayout*)layout ItemMinimumInteritemSpacingForIndexPath:(NSIndexPath *)indexPath;

// 内边距
- (UIEdgeInsets)LeeIrregularCollectionViewFlowLayout:(UICollectionViewLayout*)layout edgeInsetsInWaterflowLayoutForIndexPath:(NSIndexPath *)indexPath;

@end

@interface LeeIrregularCollectionViewFlowLayout : UICollectionViewFlowLayout

@property (nonatomic,weak) id<LeeIrregularCollectionViewFlowLayoutDelegate> leeFlowLayoutdelegate;   //-> 代理
@property (nonatomic,strong) NSMutableArray *attrsArray;        //-> 存放所有 cell headerview footer 的数组
@property (nonatomic,assign) CGFloat contentHeight;             //-> 当前高度
@property (nonatomic,assign) CGFloat currentX;                  //-> 当前cell 右边
@property (nonatomic,assign) CGFloat formerMaxY;                //-> 前一个attr Y 轴 达到的最大位置

@end

@implementation LeeIrregularCollectionViewFlowLayout

#pragma mark - override super method
/**
 * 第一步: 初始化
 */
- (void)prepareLayout{
    [super prepareLayout];
    self.contentHeight = 0.0f;
    self.currentX      = 0.0f;
    self.formerMaxY    = 0.0f;
    
    [self.attrsArray removeAllObjects];
    
    // 如果collectionview 的section == 0 直接returen
    NSInteger sectionNumber = [self.collectionView numberOfSections];
    if (sectionNumber == 0) {
        return;
    }
    
    // section > 0
    for (int i = 0; i < sectionNumber; i++) {
        NSIndexPath *headerFooterIndexPath = [NSIndexPath indexPathForItem:0 inSection:i];
        UICollectionViewLayoutAttributes *sectionHeaderAttri = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:headerFooterIndexPath];
        if (sectionHeaderAttri.frame.size.height > 0) {
            [self.attrsArray addObject:sectionHeaderAttri];
        }
        NSInteger itemNumber = [self.collectionView numberOfItemsInSection:i];
        for (int j = 0; j < itemNumber; j++) {
            NSIndexPath *itemIndexPath = [NSIndexPath indexPathForItem:j inSection:i];
            UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:itemIndexPath];
            NSAssert(attrs.frame.size.height > 0 && attrs.frame.size.width > 0 , @"item size 的高度 或 宽度 为0,这里不允许为0 ");
            if (attrs.frame.size.height > 0 && attrs.frame.size.width > 0) {
                
            }
            [self.attrsArray addObject:attrs];
        }
        
        UICollectionViewLayoutAttributes *sectionFooterAttri = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter atIndexPath:headerFooterIndexPath];
        if (sectionFooterAttri.frame.size.height > 0) {
            [self.attrsArray addObject:sectionFooterAttri];
        }
    }
}

/**
 * 第二步: 决定cell的排布
 */
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.attrsArray;
}

/*!
 *  多次调用 只要滑出范围就会 调用
 *  当CollectionView的显示范围发生改变的时候,是否重新发生布局
 *  一旦重新刷新 布局,就会重新调用
 *  1.layoutAttributesForElementsInRect:方法
 *  2.preparelayout方法
 */
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}


- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{
    
    CGSize supplementaryViewSize = CGSizeZero;
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:elementKind withIndexPath:indexPath];
    
    if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (self.leeFlowLayoutdelegate && [self.leeFlowLayoutdelegate respondsToSelector:@selector(LeeIrregularCollectionViewFlowLayout:headerViewSizeForIndexPath:)]) {
            supplementaryViewSize = [self.leeFlowLayoutdelegate LeeIrregularCollectionViewFlowLayout:self headerViewSizeForIndexPath:indexPath];
        }
        
    }else if ([elementKind isEqualToString:UICollectionElementKindSectionFooter]){
        if (self.leeFlowLayoutdelegate && [self.leeFlowLayoutdelegate respondsToSelector:@selector(LeeIrregularCollectionViewFlowLayout:FooterViewSizeForIndexPath:)]) {
            supplementaryViewSize = [self.leeFlowLayoutdelegate LeeIrregularCollectionViewFlowLayout:self FooterViewSizeForIndexPath:indexPath];
        }
    }
    
    CGRect frame =  attrs.frame;
    frame.size = supplementaryViewSize;
    frame.origin.y = self.contentHeight;
    attrs.frame = frame;
    self.contentHeight += supplementaryViewSize.height;
    return attrs;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    CGFloat collectionViewW = self.collectionView.frame.size.width;
    CGSize itemSize = [self.leeFlowLayoutdelegate LeeIrregularCollectionViewFlowLayout:self itemSizeForIndexPath:indexPath];
    
    CGFloat itemLineSpacing = 10.0f;
    if (self.leeFlowLayoutdelegate && [self.leeFlowLayoutdelegate respondsToSelector:@selector(LeeIrregularCollectionViewFlowLayout:itemMinimumLineSpacingForIndexPath:)]) {
        itemLineSpacing = [self.leeFlowLayoutdelegate LeeIrregularCollectionViewFlowLayout:self itemMinimumLineSpacingForIndexPath:indexPath];
    }
    CGFloat interItemSpacing = 10.0f;
    if (self.leeFlowLayoutdelegate && [self.leeFlowLayoutdelegate respondsToSelector:@selector(LeeIrregularCollectionViewFlowLayout:ItemMinimumInteritemSpacingForIndexPath:)]) {
        interItemSpacing = [self.leeFlowLayoutdelegate LeeIrregularCollectionViewFlowLayout:self ItemMinimumInteritemSpacingForIndexPath:indexPath];
    }
    UIEdgeInsets sectionEdge =UIEdgeInsetsMake(10.f, 10.f, 10.f, 10.f);
    if (self.leeFlowLayoutdelegate && [self.leeFlowLayoutdelegate respondsToSelector:@selector(LeeIrregularCollectionViewFlowLayout:edgeInsetsInWaterflowLayoutForIndexPath:)]) {
        sectionEdge = [self.leeFlowLayoutdelegate LeeIrregularCollectionViewFlowLayout:self edgeInsetsInWaterflowLayoutForIndexPath:indexPath];
    }
    
    NSInteger itemNumber = [self.collectionView numberOfItemsInSection:indexPath.section];
    if (itemNumber == 0) {
        attrs.frame = CGRectZero;
        return attrs;
    }
    
    CGRect currentFrame = attrs.frame;
    currentFrame.size = itemSize;
    
    CGFloat maxWidth = MIN(currentFrame.size.width, collectionViewW - sectionEdge.left - sectionEdge.right);
    currentFrame.size.width = maxWidth;
    
    if (indexPath.row == 0) {
        self.contentHeight += sectionEdge.top;
        currentFrame.origin.x = sectionEdge.left;
        currentFrame.origin.y = self.contentHeight;
    }else{
        if (self.currentX + itemLineSpacing + itemSize.width + sectionEdge.right <= collectionViewW) { //本行
            currentFrame.origin.x = self.currentX + itemLineSpacing;
            currentFrame.origin.y = self.contentHeight;
        }else{ //下一行
            self.contentHeight = self.formerMaxY + interItemSpacing;
            currentFrame.origin.x = sectionEdge.left;
            currentFrame.origin.y = self.contentHeight;
        }
    }
    
    attrs.frame = currentFrame;
    self.currentX = CGRectGetMaxX(attrs.frame);
    
    self.formerMaxY = MAX(CGRectGetMaxY(attrs.frame), self.formerMaxY);
    if (indexPath.row == (itemNumber -1) ) {
        self.contentHeight  = MAX(CGRectGetMaxY(attrs.frame) + sectionEdge.bottom,  self.formerMaxY + sectionEdge.bottom);
    }
    
    return attrs;
}

- (CGSize)collectionViewContentSize{
    return CGSizeMake(self.collectionView.frame.size.width, self.contentHeight);
}


#pragma mark - setter $ getter
- (NSMutableArray *)attrsArray{
    if (!_attrsArray) {
        _attrsArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _attrsArray;
}

在代理方法中使用

- (CGSize)LeeIrregularCollectionViewFlowLayout:(UICollectionViewLayout *)layout itemSizeForIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake([self widthForString:self.dataArray[indexPath.section][@"list"][indexPath.row][@"name"] fontSize:15 andHeight:50]+20, 50);
}

/** 头部视图Size */
- (CGSize)LeeIrregularCollectionViewFlowLayout:(UICollectionViewLayout *)layout headerViewSizeForIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, 50);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADVIEW_ID forIndexPath:indexPath];
        UILabel *label = [[UILabel alloc]init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:15];
        [headerView addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headerView.mas_left).offset(10);
            make.top.bottom.equalTo(headerView);
            make.right.equalTo(headerView.mas_right).offset(-10);
        }];
        
        label.text = self.dataArray[indexPath.section][@"title"];
        
        return headerView;
    }
    return nil;
}

在collectionview 懒加载方法中使用

 LeeIrregularCollectionViewFlowLayout *flowLaout = [[LeeIrregularCollectionViewFlowLayout alloc]init];
        flowLaout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        _baseCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLaout];
        flowLaout.leeFlowLayoutdelegate = self;
 

大功告成 效果如下

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339