iOS UICollectionView autolayout UICollectionViewCell 瀑布流加載網絡圖片自適應cell的高度章
這篇文章主要是用來給自己做記錄,防止以后忘掉
效果圖
瀑布流
網上有很多iOS的瀑布流的資料,這里只記錄UICollectionViewCell內部約束布局并且加載網絡圖片讓Cell的高度可以自適應顯示瀑布流的效果。
瀑布流的一般就是派生
UICollectionViewFlowLayout
類重寫UICollectionViewFlowLayout的
prepareLayout
方法,一次性計算所有item的frame,并創建item對應的UICollectionViewLayoutAttributes用一個數組把UICollectionViewLayoutAttributes存儲起來返回。重寫
layoutAttributesForElementsInRect
方法,返回prepareLayout
中item創建的UICollectionViewLayoutAttributes數組。
@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布局屬性,如果是高度根據手動計算出來的,那么在下面直接設置item的高度就好。(網上看到大多都是能確定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約束布局的高度,所以必須是系統自動根據約束計算出來的高度。(主要是想偷懶,不想自己去手動計算cell子控件的各個高度)使用的是
layoutAttributesForItemAtIndexPath
方法可以在下面的代碼中看到手動布局只需要根據indexPath創建UICollectionViewLayoutAttributes然后給frame進行一個賦值,更改item的位置進行瀑布流式的布局方式。
// 這里獲取item的UICollectionViewLayoutAttributes布局屬性,如果是高度根據手動計算出來的,那么在下面直接設置item的高度就好。(網上看到大多都是能確定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;
根據網絡圖片cell的高度自適應
也有其他的文章有講到網絡圖片獲取cell自適應高度,可以看看其他人的做法。
如果是cell約束布局,那么寬度是確定的,我這邊是根據圖片的寬度進行約束cell的寬度。(不會的話,可以去看看相關的文章)
因為圖片一開始是不能確定高度的,開始我們使用一個默認的高度,并且我們只能知道item的寬度,所以圖片寬度是確定的,所以圖片下載下來是需要更新圖片高度約束。
使用SDWebImage加載網絡圖片
- (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;
// 這個調用會讓所有的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);
}];
- 外部告訴圖片高度進行圖片高度約束布局更新(更新時機是個問題,大量圖片更新高度,cell需要重新布局,界面會存在跳動,并不友好。推薦大家還是盡量使用計算的結果進行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));
}];
}