Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How to display collection view cells based on screen width dynamically in iOS?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.46k
    Comment on it

    Hi Readers,

    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
                      layout:(UICollectionViewLayout *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath
        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);
        return flowLayout.itemSize;
    [Click and drag to move]


    After using this code you will get appropriate cell size and number of cells according to the screen size.

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: