iosswiftuicollectionviewnscollectionviewflowlayout

Swift: collectionView cell


I create collectionView And I have 3 cells. I want to that my cells look like this for all screens in all device:

enter image description here

But I have this result for iPad.

enter image description here

How to fix it?

Update

I add collectionView in UIViewController. I have this constraints for collectionView:

enter image description here

Sizing my cells:

enter image description here

code:

func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 3
    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let itemsPerRow: CGFloat = 3
    let itemWidth = (collectionView.bounds.width / itemsPerRow)
    let itemHeight = itemWidth * 1.5
    return CGSize(width: itemWidth, height: itemHeight)
}

Solution

  • You need to change the cell size adaptively, otherwise the size will not work for all screen sizes.

    You have your function, where you return the cell size:

    return CGSize(width: 182, height: 275)
    

    Instead, make it adaptive like this:

    return CGSize(width: self.view.frame.width / 3, height: self.view.frame.height)
    

    Or, to have the gap in-between, create an offset:

    let offset = 10
    
    let width = self.view.frame.width - offset * 4 // 4 gaps
    let height = self.view.frame.height - offset * 2 // 2 gaps
    
    return CGSize(width: width / 3, height: height) // Divide into equally-sized cells
    

    Of course, the self.view can be replaced with any container you want the cells to fit in.