tableView嵌套CollectionView,并且tableView自适应高度,collectionView自适应宽度

先上效果图
gif.gif

实现原理分为两部分:

1、tableView里面嵌套CollectionView,tableViewCell分为标题和collectionView两部分,,并且根据collectionView的cell个数来自适应高度;
2、collectionView的cell根据里面文字长度自适应宽度(也可以自适应高度,自行设置)

简单的介绍一下代码,需要demo的同学请自行移步到gitHub,如果有帮到你,请顺手给个star哦😀😀

1、tableIView就没有什么好介绍的了,最主要的就是cell的高度,我这是是根据title的高度+模型里面collectionCell的个数来计算了,如果有更好思路的童鞋,欢迎下面留言。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DCMyTableViewCell *cell = [DCMyTableViewCell cellWithTableView:tableView forRowAtIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DCCarModel *model = self.dataSource[indexPath.row];
    return 50+(model.carType.count/2+model.carType.count%2)*30;
}/*(model.carType.count/2+model.carType.count%2)这是计算有几行collectionCell,我设置的是一行有两个cell*/

2、tableViewCell内部创建collectionView,具体就直接看代码吧;值得一提的是,如果要自适应collectionCell的宽度,必须要使用layout.estimatedItemSize这个属性;

    /** 创建UICollectionViewFlowLayout的子类,固定cell之间的距离,解决如果cell是一个的话,会居中的bug */
    DCCollectionViewFlowLayout *layout = [[DCCollectionViewFlowLayout alloc]init];
    CGFloat itemWidth = ScreenWidth/2;
    // 设置每个item的大小
    layout.estimatedItemSize = CGSizeMake(itemWidth-10, 25);
    // 设置列间距
    layout.minimumInteritemSpacing = 1;
    // 设置行间距
    layout.minimumLineSpacing = 1;
    //每个分区的四边间距UIEdgeInsetsMake
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    /**
     初始化mainCollectionView
     设置collectionView的位置
     */
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.titleLabel.bottom+10, ScreenWidth, 50) collectionViewLayout:layout];
    self.collectionView.scrollEnabled = NO;
    [self.collectionView registerClass:[DCMyCollectionViewCell class] forCellWithReuseIdentifier:CellId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.collectionView];

这是赋值之后重新计算collectionView的高度

-(void)layoutSubviews {
    [super layoutSubviews];
    self.collectionView.frame = CGRectMake(0, self.titleLabel.bottom, ScreenWidth, (self.model.carType.count/2+self.model.carType.count%2)*30);
}
-(void)setModel:(DCCarModel *)model {
    _model = model;
    self.titleLabel.text = model.title;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.model.carType.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DCMyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellId forIndexPath:indexPath];
    cell.model = self.model.carType[indexPath.row];
    return cell;
}

3、 固定cell之间的距离,创建UICollectionViewFlowLayout的子类,重写layoutAttributesForElementsInRect方法,解决如果cell是一个的话,会居中的bug

/** 固定cell之间的距离 */
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray * attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    // 设置的最大间距,根据需要修改
    CGFloat maximumSpacing = 5.0;
    
    if (attributes.count > 0) {
        UICollectionViewLayoutAttributes *firstAttributes = attributes[0];
        CGRect frame = firstAttributes.frame;
        frame.origin.x = maximumSpacing;
        firstAttributes.frame = frame;
    }
    
    // 从第二个循环到最后一个
    for (NSInteger i = 1 ; i < attributes.count ; i++ ) {
        // 当前的attribute
        UICollectionViewLayoutAttributes * currentLayoutAttributes = attributes[i];
        // 上一个attribute
        UICollectionViewLayoutAttributes * prevLayoutAttributes = attributes[i - 1];
        // 前一个cell的最右边
        CGFloat origin = CGRectGetMaxX(prevLayoutAttributes.frame);
        // 如果当前一个cell的最右边加上我们的想要的间距加上当前cell的宽度依然在contentSize中,我们改变当前cell的原点位置
        // 不加这个判断的后果是,UICollectionView只显示一行,原因是下面所有的cell的x值都被加到第一行最后一个元素的后面了
        if (origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width - 30) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        } else {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }
    
    return attributes;
}

4、collectionCell的布局,实现cell的自适应,要在cell内部实现preferredLayoutAttributesFittingAttributes的方法和estimatedItemSize相配合

-(void)initView{
    self.bgView = [[UIView alloc]init];
    self.bgView.layer.cornerRadius = 9;
    self.bgView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.bgView.layer.borderWidth = 0.5;
    [self addSubview:self.bgView];
    
    self.detailLabel = [[UILabel alloc]init];
    self.detailLabel.font = [UIFont systemFontOfSize:12];
    self.detailLabel.textAlignment = NSTextAlignmentCenter;
    self.detailLabel.numberOfLines = 0;
    [self addSubview:self.detailLabel];
}
-(void)layoutSubviews {
    [super layoutSubviews];
    NSString *str = [NSString stringWithFormat:@"%@ %@辆",self.model.carType,self.model.carNum];
    CGSize maxSize = CGSizeMake((ScreenWidth-10)/2, 30);
    NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
    CGSize carSize = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    self.bgView.frame = CGRectMake(0, 0, carSize.width+10, carSize.height+4);
    self.detailLabel.frame = CGRectMake(5, 1, carSize.width, carSize.height+2);
}
-(void)setModel:(DCCarDetailModel *)model {
    _model = model;
    self.detailLabel.text = [NSString stringWithFormat:@"%@ %@辆",model.carType,model.carNum];
}
-(UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    // 获得每个cell的属性集
    UICollectionViewLayoutAttributes *attributes = [super preferredLayoutAttributesFittingAttributes:layoutAttributes];
    // 计算cell里面textfield的宽度
    //    NSString *str = [NSString stringWithFormat:@"%@-%@ %@辆",self.model.brandName,self.model.vehicleModelName,self.model.carCount];
    CGRect frame = [self.detailLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 30) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObjectsAndKeys:self.detailLabel.font,NSFontAttributeName, nil] context:nil];
    
    // 这里在本身宽度的基础上 又增加了10
    frame.size.width += 10;
    frame.size.height = 30;
    
    // 重新赋值给属性集
    attributes.frame = frame;
    
    return attributes;
}

好了,如果有不懂得童鞋,欢迎在下面留言哦,我会及时回复大家的。demo传送门

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

推荐阅读更多精彩内容