UITableViewCell上放CollectionView,cell 高度自適應(yīng)

實(shí)現(xiàn)思路

1.使用autoLayout對(duì)collectionView進(jìn)行約束,對(duì)collationView的左、右、上、下進(jìn)行約束,不約束高度。
2.對(duì)collectionView的“contentSize”進(jìn)行監(jiān)聽,當(dāng)監(jiān)聽到其contentSize發(fā)生變化后,對(duì)collectionView重新進(jìn)行約束,并約束高度。
3.注意:在collectionView的數(shù)據(jù)源發(fā)生變化后需要對(duì)collectionView進(jìn)行reloadData,并且調(diào)用collectionView的layoutIfNeeded方法。

核心代碼

 [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(self);
    }];
[self.collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentSize"]) {
        CGFloat height = self.collectionView.contentSize.height;
        [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.mas_equalTo(self);
            make.height.equalTo(@(height));
        }];
    }
}
- (void)setDataArr:(NSArray *)dataArr{
    _dataArr = dataArr;
    [self.collectionView reloadData];
    [self.collectionView layoutIfNeeded];
}

demo地址:https://github.com/yangguanghei/DynamicTableView.git

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容