How to resize the collection view cells according to device screen size? How to resize the collection view cells according to device screen size? ios ios

How to resize the collection view cells according to device screen size?


Implement sizeForItemAt method according to the view's frame size

Swift

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {    let height = view.frame.size.height    let width = view.frame.size.width    // in case you you want the cell to be 40% of your controllers view    return CGSize(width: width * 0.4, height: height * 0.4)}

Objective C

- (CGSize)collectionView:(UICollectionView *)collectionView               layout:(UICollectionViewLayout *)collectionViewLayout    sizeForItemAtIndexPath:(NSIndexPath *)indexPath {   CGFloat height = self.view.frame.size.height;   CGFloat width  = self.view.frame.size.width;   // in case you you want the cell to be 40% of your controllers view   return CGSizeMake(width * 0.4, height * 0.4); }


Swift 4

Multiply the collectionView's frame width/height in an implementation of the sizeForItemAt method.

class yourClassName: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {            return CGSize(width: self.myCollectionView.frame.height / 6 * 5, height: self.myCollectionView.frame.height / 6 * 5)        }}

self.myCollectionView is the reference from you collection view Item
it's important to implement UICollectionViewDelegateFlowLayout

And because it will not fit another cell you will have only one row.


You should try using a simple equation when setting your cell size instead of number like so:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {        return CGSize(width: view.frame.width / 2, height: 350)    }

dividing it by 2 will mean that the cell always be half of the screens size, taking away and kind of minimumLineSpacing functions and/or and UIEdgeInset methods you have called. Hope this helps.


matomo