Zayd Bhyat Zayd Bhyat - 3 months ago 51
iOS Question

Adjusting UICollectionViewFlowLayout cells on rotation

So I'm working on an app that is part of an ePub framework. The app embeds the reader into its view and allows a user to scroll zoom and page by swipe. Im trying to modify it so that the list of ePubs comes into a collectionview as cells displaying the cover image of the epubs. I can create the cells for the flowlayout and using the frame bounds I can create cells but when I try and rotate from portrait to landscape they dont adjust in size and position. My code for the cells is this:

//Set Collection View Cell Size and Orientation
collectionView:(UICollectionView *) collectionView
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

//Set Landscape size of cells
if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-350;
NSLog(@"Is Landscape");
return CGSizeMake(cellWidth, cellHeigt);
//Set Potrait size of cells
NSLog(@"Is Portrait");
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-80;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-240;
return CGSizeMake(cellWidth, cellHeigt);

and I use this code to position them:

//Collection View Cell Position
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {

if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)){
return UIEdgeInsetsMake(0,10,0,20); // top, left, bottom, right
return UIEdgeInsetsMake(0,20,0,20); // top, left, bottom, right

When I rotate the device the cells top boundary goes over the frame.

Please help, how can I update the frame dynamically?


You need to refresh collection while rotation . try following code :

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
    [yourCollectionview performBatchUpdates:nil completion:nil];