我在这里试图为collectionView
实现动态单元格高度。
所以这是我的情况:
我有一个UICollectionViewCell
xib文件,其中包含以下控件及其约束以实现动态单元格高度:
UIButton
UILabel (Fixed Height)
UILabel (Fixed Height)
UILabel (Dynamic Height)
如下图所示:
当UIButton
具有固定高度(130)并且最后UILabel
的动态文本为图像#1时,一切正常,直到我更改了UIButton
的约束如下:
添加宽高比(1:1)。
如图2所示:
图片#1
图片#2
对于代码方,这是我做的:
1 - UICollectionViewCell
子类:
-(void)awakeFromNib {
[super awakeFromNib];
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.contentView.translatesAutoresizingMaskIntoConstraints = YES;
}
-(void)layoutSubviews {
[self layoutIfNeeded];
}
-(CGSize)preferredLayoutSizeFittingSize:(CGSize)targetSize
{
CGRect originalFrame = self.frame;
CGRect frame = self.frame;
frame.size = targetSize;
self.frame = frame;
[self setNeedsLayout];
[self layoutIfNeeded];
CGSize computedSize = [self systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
CGSize newSize = CGSizeMake(targetSize.width, computedSize.height);
self.frame = originalFrame;
return newSize;
}
并在我的ViewController
内部实现了UICollectionView
委托:
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.arrData.count;
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
BEBuyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.reuseID forIndexPath:indexPath];
if([cell isKindOfClass:NSClassFromString(@"BEReceiverCollectionViewCell")])
{
cell.isReceiver = YES;
cell.iType = indexPath.item+1;
}
cell.object = self.arrData[indexPath.row];
[cell fillData];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat width = [(BECollectionViewFlowLayout*)collectionViewLayout itemWidth];
CGSize targetSize = CGSizeMake(width, 0);
if(sizingCell == nil)
{
UINib *nibFile = [UINib nibWithNibName:@"CustomCell" bundle:nil];
sizingCell = [[nibFile instantiateWithOwner:self options:nil] firstObject];
}
sizingCell.object = self.arrData[indexPath.row];
[sizingCell fillData];
CGSize adequateSize = [sizingCell preferredLayoutSizeFittingSize:targetSize];
CGSize size = CGSizeMake(width, adequateSize.height + iOffset*2);
return size;
}
注意:BECollectionViewFlowLayout是一个自定义UICollectionViewFlowLayout
,可以通过自定义UICollectionView
UICollectionView
显示2列
那么我缺少什么来实现我的collectionView正确的动态高度?