Search code examples
swiftuicollectionviewautolayout

UICollectionViewLayout Not Resizing UIImageViews Within Cells


My collectionview images are not getting resized. I'm using the following in the viewcontroller that contains the collectionview, and it sizes correctly when the cells are empty; however with an imageview inside it doesn't behave properly.

Thanks!

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let noOfCellsInRow = 2
    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
    let totalSpace = flowLayout.sectionInset.left
        + flowLayout.sectionInset.right
        + (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1))
    let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow))
    return CGSize(width: size, height: size)

}

enter image description here


Solution

  • Add this to your ViewController

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        collectionView.collectionViewLayout.invalidateLayout()
    }
    

    And in Storyboard check if the collection view - Estimate Size is set to None in Size Inspector