實(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];
}