UICollectionView接口旋转与自定义布局

Stu*_*art 7 ios uicollectionview uicollectionviewlayout

旋转设备时,我看到UICollectionView了自定义布局(子类UICollectionViewLayout)的一些神秘行为.

我有一个简单的水平滚动的单元格行.当设备从纵向旋转到横向时,之前看不到的其他单元格变得可见,并且那些出现的单元格的动画是错误的(它使用熟悉的重影效果,我认为这是集合视图的某种默认动画效果布局).请注意此动画中最左侧出现的单元格:

UICollectionViewRotationGhosting

有关自定义布局设置的一些细节:

  • shouldInvalidateLayoutForBoundsChange:回报YES.
  • layoutAttributesForItemAtIndexPath:缓存字典中的属性(如果尚未创建).
  • layoutAttributesForElementsInRect:我计算哪些单元格应该是手工可见的,并且centre每次稍微调整它们的属性,然后返回它们的属性.

然后我有以下代码来处理初始/最终布局属性:

- (void)prepareForAnimatedBoundsChange:(CGRect)oldBounds
{
    [super prepareForAnimatedBoundsChange:oldBounds];
    self.animatingBoundsChange = YES;
}

- (void)finalizeAnimatedBoundsChange
{
    [super finalizeAnimatedBoundsChange];
    self.animatingBoundsChange = NO;
}

- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath
{
    if (self.animatingBoundsChange) {
        // If the view is rotating, appearing items should animate from their current attributes (specify `nil`).
        // Both of these appear to do much the same thing:
        //return [self layoutAttributesForItemAtIndexPath:itemIndexPath];
        return nil;
    }
    return [super initialLayoutAttributesForAppearingItemAtIndexPath:itemIndexPath];
}

- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDisappearingItemAtIndexPath:(NSIndexPath *)itemIndexPath
{
    if (self.animatingBoundsChange) {
        // If the view is rotating, disappearing items should animate to their new attributes.
        return [self layoutAttributesForItemAtIndexPath:itemIndexPath];
    }
    return [super finalLayoutAttributesForDisappearingItemAtIndexPath:itemIndexPath];
}
Run Code Online (Sandbox Code Playgroud)

在我看来,最初的布局属性新出现的细胞都有点不正确的(它结束在正确的位置毕竟).但是当我记录centerinitalLayout...方法返回的布局属性的属性时,一切看起来都是正确的 - 所有都沿着水平轴均匀分布.

没有正确动画的单元格的唯一区别特征是,在调用方法[collectionView visibleCells]时,它的单元格不会在数组中返回initialLayout....在layoutAttributesForElementsInRect:它之前的那个确实正确地确定了它的布局属性.

发生什么了?对引擎盖下发生的事情的一些见解会非常有用...... UICollectionView看起来像一个巨大的黑盒子.

Joh*_*rug 0

基于Arun_k 链接到的答案,似乎您可能需要为出现的新单元格返回与initialLayoutAttributesForAppearingItemAtIndexPath:except不同的东西。适用于屏幕上已经存在的单元格,但可能不适合返回新单元格。也许您可以尝试在此方法中为所有单元格返回一个固定值,看看它是否改变了新插入单元格的动画行为,然后从那里继续。nilnilUICollectionViewLayoutAttributes

这个问题进一步阐明了这个问题:initialLayoutAttributesForAppearingItemAtIndexPath针对所有可见单元格触发,而不仅仅是插入的单元格