动态UICollectionView内容大小高度太长

时间:2014-08-23 01:34:11

标签: ios uicollectionview uicollectionviewcell uicollectionviewlayout contentsize

我需要根据每个单元格的图像视图高度创建一个具有动态高度的UICollectionView单元格。我已经从UICollectionViewFlowLayout创建了一个子类来实现所需的行为,如下所示:

#define numColumns 2

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {

    NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];

    for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) {

        if (attributes.representedElementKind == nil) {

            NSIndexPath* indexPath = attributes.indexPath;
            attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;

        }

    }

   return attributesToReturn;

}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewLayoutAttributes* currentItemAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];

    if (indexPath.item < numColumns) {

        CGRect frame = currentItemAttributes.frame;
        frame.origin.y = 5;
        currentItemAttributes.frame = frame;

        return currentItemAttributes;

    }

    NSIndexPath* indexPathPrev = [NSIndexPath indexPathForItem:indexPath.item-numColumns inSection:indexPath.section];
    CGRect framePrev = [self layoutAttributesForItemAtIndexPath:indexPathPrev].frame;
    CGFloat YPointNew = framePrev.origin.y + framePrev.size.height + 10;
    CGRect frame = currentItemAttributes.frame;
    frame.origin.y = YPointNew;
    currentItemAttributes.frame = frame;

    return currentItemAttributes;

}

在集合视图中,控制器委托流程布局

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    float imageHeight = [[(Product *)self.products[indexPath.row] image] height];
    float imageWidth = [[(Product *)self.products[indexPath.row] image] width];

    float ratio = 150.0/imageWidth;

    return CGSizeMake(150, ratio*imageHeight);

}

单元格实施

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    ProductCell *cell = (ProductCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:@"ProductCell" forIndexPath:indexPath];

    ....

    [cell.imageView setImageWithURL:[NSURL URLWithString:[[(Product *)self.products[indexPath.row] image] url]]];

    return cell;

}

所有单元格都按预期显示,但内容视图太长,如图所示。

Dynamic UICollectionView height

我想我必须实现方法 - (CGSize)collectionViewContentSize来获取正确的contentSize,但我不知道如何计算集合视图的实际高度

0 个答案:

没有答案