UITableViewCell上放CollectionView,cell 高度自适应

实现思路

1.使用autoLayout对collectionView进行约束,对collationView的左、右、上、下进行约束,不约束高度。
2.对collectionView的“contentSize”进行监听,当监听到其contentSize发生变化后,对collectionView重新进行约束,并约束高度。
3.注意:在collectionView的数据源发生变化后需要对collectionView进行reloadData,并且调用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 *)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

你可能感兴趣的:(UITableViewCell上放CollectionView,cell 高度自适应)