Change UICollectionViewCell size on different device orientations

后端 未结 6 600
刺人心
刺人心 2020-12-12 09:36

I am using an UICollectionView with UICollectionViewFlowLayout.

I set the size of each cell through the

collectionView:lay         


        
6条回答
  •  既然无缘
    2020-12-12 10:32

    I solved using two UICollectionViewFlowLayout. One for portrait and one for landscape. I assign them to my collectionView dinamically in -viewDidLoad

    self.portraitLayout = [[UICollectionViewFlowLayout alloc] init];
    self.landscapeLayout = [[UICollectionViewFlowLayout alloc] init];
    
    UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
    
    if (UIInterfaceOrientationIsPortrait(orientationOnLunch)) {
        [self.menuCollectionView setCollectionViewLayout:self.portraitLayout];
    } else {
        [self.menuCollectionView setCollectionViewLayout:self.landscapeLayout];
    }
    

    Then I simply modified my collectionViewFlowLayoutDelgate Methods like this

    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
        CGSize returnSize = CGSizeZero;
    
        if (collectionViewLayout == self.portraitLayout) {
            returnSize = CGSizeMake(230.0, 120.0);
        } else {
            returnSize = CGSizeMake(315.0, 120.0);
        }
    
        return returnSize;
    }
    

    Last I switch from a layout to one other on rotation

    - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
        if (UIInterfaceOrientationIsPortrait(fromInterfaceOrientation)) {
            [self.menuCollectionView setCollectionViewLayout:self.landscapeLayout animated:YES];
        } else {
            [self.menuCollectionView setCollectionViewLayout:self.portraitLayout animated:YES];
        }
    }
    

提交回复
热议问题