UICollectionView 布局更新 - 单元格大小未改变

8

我遇到了关于collectionView项大小的问题。我想在竖屏模式下显示3个项目,横屏模式下显示6个项目。我已经设置了-layoutSubviews如下:

- (void)layoutSubviews {
    [super layoutSubviews];

    if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait || ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown)) {
        //Portrait orientation
        self.flowLayoutPortrait.itemSize = CGSizeMake(106, 106);

    } else if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeLeft || ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeRight)) {
        //Landscape orientation
        self.flowLayoutPortrait.itemSize = CGSizeMake(93, 93);
    }
    [self.collectionView.collectionViewLayout invalidateLayout];
}

但是单元格大小不会更新,对于两种方向都保持不变。如果我创建了2个FlowLayouts并使用:

[self.collectionView setCollectionViewLayout:self.flowLayoutLandscape];

一切都正常,但我真的不喜欢它们被改变的方式。动画效果非常糟糕。由于只需要更新itemSize属性,因此使用1个布局似乎是最好的选择。

我该如何告诉collectionView更新布局呢?

2个回答

15

我使用了这种方法,对我来说非常好:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isLandscape)
        return CGSizeMake(yourLandscapeWidth, yourLandscapeHeight);
    else
        return CGSizeMake(yourNonLandscapeWidth, yourNonLandscapeHeight);
}

7
谢谢,这非常有效!对于日后的读者,还需要在 willRotateToInterfaceOrientation: 中添加 [collectionView.collectionViewLayout invalidateLayout] - Armands L.

0
也许你可以使用不同的标识符为纵向/横向模式创建不同的单元格.. 然后只需重新加载集合视图的数据,它就一定会起作用。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait || ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown)) {
        //Portrait orientation
        //dequeue cell for portrait mode

    } else if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeLeft || ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeRight)) {
        //Landscape orientation
        //dequeue cell for landscape mode
    }

    return cell;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接