Stefano Mtangoo
Stefano Mtangoo

Reputation: 6550

Make UICollectionViewCell same width as UICollectionView

Am writing this question just as a reference and to help anyone facing the same issue I faced. Many answers here at SO and in google search didn't provide a complete solution. So Here I answer my own question

Upvotes: 0

Views: 41

Answers (1)

Stefano Mtangoo
Stefano Mtangoo

Reputation: 6550

Here is the code that works and sets both width and height correctly

import UIKit

class MyViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    @IBOutlet weak var myCollectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        myCollectionView.delegate = self
        myCollectionView.reloadData()
    }

    //Other methods here

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.size.width
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) //Put your Cell Identifier istead of Cell
        let height = cell.contentView.frame.height

        return CGSize(width: width, height: height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return .zero
    }
}

Upvotes: 2

Related Questions