iOS UICollectionView autolayout UICollectionViewCell 瀑布流加載網(wǎng)絡(luò)圖片自適應(yīng)cell的高度章
這篇文章主要是用來給自己做記錄,防止以后忘掉
效果圖
瀑布流
網(wǎng)上有很多iOS的瀑布流的資料蔚龙,這里只記錄UICollectionViewCell內(nèi)部約束布局并且加載網(wǎng)絡(luò)圖片讓Cell的高度可以自適應(yīng)顯示瀑布流的效果冰评。
瀑布流的一般就是派生
UICollectionViewFlowLayout
類重寫UICollectionViewFlowLayout的
prepareLayout
方法,一次性計算所有item的frame木羹,并創(chuàng)建item對應(yīng)的UICollectionViewLayoutAttributes用一個數(shù)組把UICollectionViewLayoutAttributes存儲起來返回甲雅。重寫
layoutAttributesForElementsInRect
方法,返回prepareLayout
中item創(chuàng)建的UICollectionViewLayoutAttributes數(shù)組汇跨。
@interface MSPinterestFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, assign) NSInteger columnCount;
@end
@interface MSPinterestFlowLayout ()
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *layoutAttributes;
@property (nonatomic, strong) NSArray<NSNumber *> *heightsForColumnArray;
@end
@implementation MSPinterestFlowLayout
- (void)prepareLayout
{
[super prepareLayout];
[_layoutAttributes removeAllObjects];
NSInteger column = self.columnCount;
NSInteger section = 0;
NSInteger numberOfItem = [self.collectionView numberOfItemsInSection:section];
NSMutableArray<NSNumber *> *allColumnMaxY = [NSMutableArray array];
for (int currentColumn = 0; currentColumn < column; currentColumn++)
{
allColumnMaxY[currentColumn] = @(0);
}
for (int index = 0; index < numberOfItem; index++)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:section];
CGFloat minColumnMaxY = allColumnMaxY[0].floatValue;
NSInteger itemColumn = 0;
for (int columnIndex = 0; columnIndex < column; columnIndex++)
{
CGFloat columnMaxyValue = allColumnMaxY[columnIndex].floatValue;
if (minColumnMaxY > columnMaxyValue)
{
minColumnMaxY = columnMaxyValue;
itemColumn = columnIndex;
}
}
// 這里獲取item的UICollectionViewLayoutAttributes布局屬性务荆,如果是高度根據(jù)手動計算出來的,那么在下面直接設(shè)置item的高度就好穷遂。(網(wǎng)上看到大多都是能確定item高度的瀑布流布局方式)
UICollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForItemAtIndexPath:indexPath];
CGRect frame = layoutAttributes.frame;
CGSize size = frame.size;
CGFloat itemY = minColumnMaxY + self.minimumLineSpacing;
CGFloat itemX = self.sectionInset.left + (self.minimumInteritemSpacing + size.width) * itemColumn;
CGRect itemRect = CGRectMake(itemX, itemY, size.width, size.height);
layoutAttributes.frame = itemRect;
[self.layoutAttributes addObject:layoutAttributes];
allColumnMaxY[itemColumn] = @(CGRectGetMaxY(itemRect));
}
_heightsForColumnArray = allColumnMaxY;
}
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
return self.layoutAttributes;
}
- (CGSize)collectionViewContentSize {
CGSize size = [super collectionViewContentSize];
if (_heightsForColumnArray.count == 0) {
return size;
}
CGFloat height = _heightsForColumnArray[0].floatValue;
for (int i = 0; i < _heightsForColumnArray.count; i++)
{
if (height < _heightsForColumnArray[i].floatValue)
{
height = _heightsForColumnArray[i].floatValue;
}
}
return CGSizeMake(size.width, height + self.sectionInset.bottom);
}
#pragma mark - Getter
- (NSMutableArray<UICollectionViewLayoutAttributes *> *)layoutAttributes
{
if (!_layoutAttributes)
{
_layoutAttributes = [NSMutableArray<UICollectionViewLayoutAttributes *> array];
}
return _layoutAttributes;
}
- (CGFloat)itemWidth
{
if (_itemWidth == 0)
{
NSInteger column = self.columnCount;
CGFloat itemWidth = (CGRectGetWidth(self.collectionView.frame) - self.sectionInset.left - self.sectionInset.right - (column - 1) * self.minimumInteritemSpacing) / column;
_itemWidth = itemWidth;
}
return _itemWidth;
}
@end
約束布局的Cell item的高度獲取函匕。
這邊特別描述一下約束布局Cell的高度獲取方法
因為我想拿到cell約束布局的高度,所以必須是系統(tǒng)自動根據(jù)約束計算出來的高度蚪黑。(主要是想偷懶盅惜,不想自己去手動計算cell子控件的各個高度)使用的是
layoutAttributesForItemAtIndexPath
方法可以在下面的代碼中看到手動布局只需要根據(jù)indexPath創(chuàng)建UICollectionViewLayoutAttributes然后給frame進(jìn)行一個賦值,更改item的位置進(jìn)行瀑布流式的布局方式中剩。
// 這里獲取item的UICollectionViewLayoutAttributes布局屬性,如果是高度根據(jù)手動計算出來的抒寂,那么在下面直接設(shè)置item的高度就好结啼。(網(wǎng)上看到大多都是能確定item高度的瀑布流布局方式)
UICollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForItemAtIndexPath:indexPath];
CGRect frame = layoutAttributes.frame;
CGSize size = frame.size;
CGFloat itemY = minColumnMaxY + self.minimumLineSpacing;
CGFloat itemX = self.sectionInset.left + (self.minimumInteritemSpacing + size.width) * itemColumn;
CGRect itemRect = CGRectMake(itemX, itemY, size.width, size.height);
layoutAttributes.frame = itemRect;
根據(jù)網(wǎng)絡(luò)圖片cell的高度自適應(yīng)
也有其他的文章有講到網(wǎng)絡(luò)圖片獲取cell自適應(yīng)高度,可以看看其他人的做法。
如果是cell約束布局屈芜,那么寬度是確定的郊愧,我這邊是根據(jù)圖片的寬度進(jìn)行約束cell的寬度。(不會的話井佑,可以去看看相關(guān)的文章)
因為圖片一開始是不能確定高度的属铁,開始我們使用一個默認(rèn)的高度,并且我們只能知道item的寬度躬翁,所以圖片寬度是確定的焦蘑,所以圖片下載下來是需要更新圖片高度約束。
使用SDWebImage加載網(wǎng)絡(luò)圖片
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MSHomeCellModel *model = _models[indexPath.row];
MSHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_kCellIdentifier forIndexPath:indexPath];
cell.imageHeight = 10;
cell.width = ((MSPinterestFlowLayout *)collectionView.collectionViewLayout).itemWidth;
cell.title = model.title;
cell.avatarURL = model.avatarURL;
cell.attentionNUmber = model.attentionNUmber;
cell.nickname = model.nickname;
cell.isAttention = model.isAttention;
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imageURL] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
if (model.isCalculateImageHeight)
{
cell.imageHeight = model.imageHeight;
}else
{
CGFloat height = (image.size.height / image.size.width) * cell.width;
cell.imageHeight = height;
model.imageHeight = height;
model.isCalculateImageHeight = YES;
// 這個調(diào)用會讓所有的item全部重新布局盒发。
[collectionView reloadItemsAtIndexPaths:@[indexPath]];
}
}];
return cell;
}
cell布局
- 最后放上cell布局的代碼
[self.contentView addSubview:self.imageView];
[self.contentView addSubview:self.titleLabel];
[self.contentView addSubview:self.avatarImageView];
[self.contentView addSubview:self.nicknameLabel];
[self.contentView addSubview:self.attentionButton];
[_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.equalTo(@(0));
make.height.greaterThanOrEqualTo(@(_kImageViewDefaultHeight));
}];
[_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.imageView.mas_bottom).offset(9);
make.left.equalTo(@(10));
make.right.lessThanOrEqualTo(@(-10));
}];
[_avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.titleLabel.mas_bottom).offset(17);
make.left.equalTo(self.titleLabel);
make.width.height.equalTo(@(20));
}];
[_nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.avatarImageView.mas_right).offset(4);
make.right.lessThanOrEqualTo(@(-50));
make.centerY.equalTo(self.avatarImageView);
}];
[_attentionButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(@(-10));
make.centerY.equalTo(self.nicknameLabel);
make.bottom.equalTo(@(-15));
}];
[self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.equalTo(self.imageView);
make.bottom.equalTo(self.attentionButton.mas_bottom).offset(15);
}];
- 外部告訴圖片高度進(jìn)行圖片高度約束布局更新(更新時機(jī)是個問題例嘱,大量圖片更新高度,cell需要重新布局宁舰,界面會存在跳動拼卵,并不友好。推薦大家還是盡量使用計算的結(jié)果進(jìn)行cell的size明吩,只需要把高度在
flowLayout
中存儲就行)
- (void)p_resetImageViewConstraints
{
CGFloat imageWidth = 50;
CGFloat imageHeight = _kImageViewDefaultHeight;
if (_width > 0) {
imageWidth = _width;
}
if (_imageHeight > 0) {
imageHeight = _imageHeight;
}
[_imageView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.top.left.equalTo(@(0));
make.width.equalTo(@(imageWidth));
make.height.equalTo(@(imageHeight));
}];
}