Search code examples
swiftxcodeimageuicollectionviewcell

Collection cell size changes according to downloaded image


    let sectionInsets = UIEdgeInsets(top: 50.0,left: 20.0,bottom: 50.0,right: 20.0)


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let paddingSpace = sectionInsets.left * (itemsPerRow + 0.5)
    let availableWidth = view.frame.width - paddingSpace
    let widthPerItem = availableWidth / itemsPerRow

    let size = CGSize(width: widthPerItem, height: widthPerItem)
    return size
    }

This is my code. Can someone tell me why the size of cell changes according to the image downloaded and also the solution of it?

I also get an issue in my debugger - "Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger."


Solution

  • Set Estimate Size to None in the Interface Builder and override the function "willTransition(to newCollection: with coordinator:)" as below:-

        public override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        let paddingSpace = sectionInsets.left * (itemsPerRow + 0.5)
        let availableWidth = view.frame.width - paddingSpace
        let widthPerItem = availableWidth / itemsPerRow
    
        let size = CGSize(width: widthPerItem, height: widthPerItem)
    
        super.viewWillTransition(to: size, with: coordinator)
    
        coordinator.animate(alongsideTransition: { (context) in
            self.imageCollectionView.collectionViewLayout.invalidateLayout()
        }) { (context) in
    
        }
    }