大型UICollectionViewCell在滚动时消失

时间:2013-07-15 15:07:55

标签: ios uicollectionview uicollectionviewcell

我遇到了与here相同的问题,即大的UICollectionViewCell(显然是UICollectionView高度的两倍以上)在给定的滚动偏移处消失,然后在给定的滚动偏移之后重新出现。

我已经实现了@JonathanCichon solution,它是UICollectionView的子类并在_visibleBounds上执行自定义操作(我知道它是一个私有API,但无论如何,我都不需要在Apple Store上提交它)

这是我的自定义集合视图:

#import "CollectionView.h"

@interface UICollectionView ()

- (CGRect)_visibleBounds;

@end

@implementation CollectionView

- (CGRect)_visibleBounds
{
    CGRect rect = [super _visibleBounds];
    rect.size.height = [self heightOfLargestVisibleCell];
    return rect;
}

- (CGFloat)heightOfLargestVisibleCell
{
    // get current screen height depending on orientation
    CGFloat screenSize = [self currentScreenHeight];

    CGFloat largestCell = 0;

    NSArray *visibleCells = self.visibleCells;

    // get the largest height between visibleCells
    for (UITableViewCell *c in visibleCells)
    {
        CGFloat h = c.frame.size.height;
        largestCell = h > largestCell ? h : largestCell;
    }

    // return higher value between screen height and higher visible cell height
    return MAX(largestCell, screenSize);
}

这有效,滚动时不再消失,但我仍有问题:如果我的滚动位置位于大单元格中间时执行reloadData,它会像之前一样消失... 我注意到在重新加载数据后,visibleCells返回nil(在我的heightOfLargestVisibleCell方法中),因此我的屏幕高度为_visibleBounds,但由于屏幕高度<当前可见的单元格高度,这个不显示...

有人已经遇到过这个问题吗?

提前谢谢

1 个答案:

答案 0 :(得分:1)

我找到了解决问题的方法。我存储heightOfLargestVisibleCell计算的值,并在重新加载数据后返回最后一个值。

@interface CollectionView : UICollectionView
@property (nonatomic, assign) CGFloat lastLargestCellHeight;
@property (nonatomic, assign) BOOL shouldEvalLargestCellHeight;

@end

@implementation CollectionView

- (CGRect)_visibleBounds
{
    CGRect rect = [super _visibleBounds];
    rect.size.height = [self heightOfLargestVisibleCell];
    return rect;
}


- (CGFloat)heightOfLargestVisibleCell
{
    if (self.shouldEvalLargestCellHeight) {
        // get current screen height depending on orientation
        CGFloat screenSize = self.frame.size.height;

        CGFloat largestCell = 0;

        NSArray *visibleCells = self.visibleCells;

        // get the largest height between visibleCells
        for (UITableViewCell *c in visibleCells)
        {
            CGFloat h = c.frame.size.height;
            largestCell = h > largestCell ? h : largestCell;
        }
        //return higher value between screen height and higher visible cell height
        self.lastLargestCellHeight = MAX(largestCell, screenSize);
        self.shouldEvalLargestCellHeight = NO;
    }
    return self.lastLargestCellHeight;
}

- (void)reloadData
{
    self.shouldEvalLargestCellHeight = NO;
    [super reloadData];
}

- (void)setContentOffset:(CGPoint)contentOffset
{
    self.shouldEvalLargestCellHeight = YES;
    [super setContentOffset:contentOffset];
}

@end