estimatedItemSize是iOS 8中蘋果最新推出的黑魔法锨并,可以讓CollectionView中也能讓 cell 自適應內(nèi)容大小,達到自動適應高度的預期效果喊儡!
UICollectionView的高度自適應的原理:
1.CollectionView根據(jù) layout 的 estimatedItemSize 算出估計的 contentSize敬察,有了 contentSize CollectionView就開始顯示
2.CollectionView 在顯示的過程中,即將被顯示的 cell 根據(jù) autolayout 的約束算出自適應內(nèi)容的 size
3.layout 從 CollectionView 里獲取更新過的 size attribute
4.layout 返回最終的 size attribute 給 CollectionView
5.CollectionView 使用這個最終的 size attribute 展示 cell
UICollectionView的高度自適應的實現(xiàn):
1. 設置 estimatdItemSize
設置 UICollectionViewFlowLayout 的 estimatdItemSize 的預估高度
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.estimatedItemSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width, 200);
estimatdItemSize 的默認值為 CGSizeZero ,所以要給一個非0值開啟高度估算镊掖。
//解決ios8上自動布局的問題
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
? ? return YES;
}
2.對cell 進行約束添加
#import"LastCell.h"
#import"Masonry.h"
@implementationLastCell
-(instancetype)initWithFrame:(CGRect)frame{
self= [super initWithFrame: frame];
if(self) {
self.backgroundColor= [UIColor whiteColor];
self.testLabel= [UILabel new];
[self.contentView addSubview: self.testLabel];
self.testImage= [UIImageView new];
[self.contentView addSubview: self.testImage];
self.testLabel.numberOfLines=0;
self.testImage.backgroundColor= [UIColor redColor];
self.testLabel.backgroundColor= [UIColor purpleColor];
[self creatAutoLayout];
}
returnself;
}
- (void)creatAutoLayout{
[self.contentView mas_makeConstraints:^(MASConstraintMaker*make) {
make.left.top.mas_equalTo(0);
make.width.mas_equalTo(300);
make.bottom.mas_equalTo(self.testLabel.mas_bottom).offset(12.0);
}];
[self.testImage mas_makeConstraints:^(MASConstraintMaker*make) {
make.left.width.top.mas_equalTo(self.contentView);
make.height.mas_equalTo(150);
}];
[self.testLabel mas_makeConstraints:^(MASConstraintMaker*make) {
make.top.mas_equalTo(self.testImage.mas_bottom).offset(10.0);
make.left.width.mas_equalTo(self.testImage);
}];
}
- (UICollectionViewLayoutAttributes*)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes*)layoutAttributes {
[self setNeedsLayout];
[self layoutIfNeeded];
CGSize size = [self.contentView systemLayoutSizeFittingSize: layoutAttributes.size];
CGRect cellFrame = layoutAttributes.frame;
cellFrame.size.height= size.height;
layoutAttributes.frame= cellFrame;
return layoutAttributes;
}
@end