In this blog we will get to know how to resize collection view cell dynamically and according to the screensize of iPhone.
Here is a very simple code given below to perform this task in a very easy way. We will use a method inside which we will resize the cell of collection view and also specify how many cells we need at one time on screen.
- (CGSize)collectionView:(UICollectionView *)collectionView
CGSize defaultSize = [(UICollectionViewFlowLayout*)collectionViewLayout itemSize]; //With the help of this line of code we will get the default size of cell
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width; // Here we get the screen width
int kCellsPerRow=(screenWidth/defaultSize.width); //number of cell display according to screen size
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)collectionView.collectionViewLayout;
CGFloat availableWidthForCells = collectionView.frame.size.width - flowLayout.sectionInset.left-20 - flowLayout.sectionInset.right-20; // calculation for width of cells
CGFloat cellWidth = availableWidthForCells / kCellsPerRow; // width of each item within cell
flowLayout.itemSize = CGSizeMake(cellWidth, flowLayout.itemSize.height);
[Click and drag to move]
After using this code you will get appropriate cell size and number of cells according to the screen size.