Collection View不会更新Rotation的布局

时间:2015-06-26 04:29:48

标签: ios objective-c uicollectionview uicollectionviewlayout

这是应用程序处于纵向模式时的视图。 enter image description here

当它旋转到横向模式时,它看起来像这样

enter image description here

视图调试程序显示UIWindow未旋转,如此处所示enter image description here

UICollectionViewController是通过StoryBoard创建的。我已经尝试了实现UICollectionViewFlowLayout的{​​{1}}子类化,但它并没有解决我的问题。

shouldInvalidateLayoutForBoundsChange

请提供接下来要检查的内容或要求调试其他代码的请求。

编辑 - 正如MirekE所建议的那样,我试图向- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { CGRect oldBounds = self.collectionView.bounds; if (CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds)) { return YES; } return NO; } 添加约束,但无法进行约束。 Editor-> Pin的所有选项都不适用于CollectionViewenter image description here

编辑,回应安德里亚 -

我的目标是iOS8.3。我的理解是旋转时调用的主要方法是CollectionView,它来自viewWillTransitionToSize:withTransitionCoordinator: protocol。我已将以下内容添加到我的CollectionViewController中,但同样的问题仍然存在

UIContentContainer

4 个答案:

答案 0 :(得分:10)

我不知道您定位的是哪个iOS版本,但我想你知道视图控制器中调用的旋转过程和方法正在发生。
在其中一种方法中,您只需要调用:

[self.collectionView.collectionViewLayout invalidateLayout];

可能取决于您的布局-reloadData
不需要子类。


编辑

我使用这种方法,我想这是行不通的,因为你应该在调整后重新调整集合:

- (void) willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super willTransitionToTraitCollection:newCollection withTransitionCoordinator:coordinator];


    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [self.collectionView.collectionViewLayout invalidateLayout];            
    } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [self.collectionView reloadData];
    }];

}


我正在做什么将布局失效过程附加到动画过程。

答案 1 :(得分:5)

如果您有UICollectionViewLayout的自定义实现,请尝试覆盖方法:

override public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
    let bounds = self.collectionView!.bounds;
    return ((CGRectGetWidth(newBounds) != CGRectGetWidth(bounds) ||
        (CGRectGetHeight(newBounds) != CGRectGetHeight(bounds))));
}

override public func invalidateLayout() {
    cache.removeAll()  // remove layout attributes ans settings if they exist
    super.invalidateLayout()

}

干杯!

答案 2 :(得分:1)

看起来您只是在画布上拖动集合视图,但没有添加任何约束。因此,当您旋转设备时,大小不会改变。

在故事板中选择集合视图,然后单击Xco​​de底部的Pin图标并添加顶部,左侧,底部和右侧边距的约束。执行此操作后,集合视图应在轮换时调整大小。

答案 3 :(得分:1)

The problem was that the collectionView outlet was not properly set. After setting the collectionView, all works properly.

collectionView outlet not set:

enter image description here

collectionView outlet set:

enter image description here