Search code examples
swiftuicollectionviewuiimageviewuiimageuicollectionviewlayout

UICollectionViewLayout Not working with UIImage in Swift 5 and Xcode 11


Please check this attached code and screen short. It's work fine when I set the color of container view but when I add UIImage in cell then it's not working. I changed the imageview content mode but it's not working.

class ViewController: UIViewController {

@IBOutlet weak var segColumn: UISegmentedControl!
@IBOutlet weak var collectionView: UICollectionView!

fileprivate var items: [UIImage] = [ // My images ]

override func viewDidLoad() {
    super.viewDidLoad()
    self.setup()
}
}

extension ViewController: UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.imgCell.image = items[indexPath.row]
    cell.imgCell.contentMode = .scaleAspectFill
    cell.contentView.backgroundColor = .red
    return cell
}
}

extension ViewController: UICollectionViewDelegateFlowLayout{

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


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 2
    }
}

Not working with UIImage

working when remove UIImage


Solution

  • Please try this solution. I think there are some changes from Xcode 11. Change the CollectionView Estimate Size to None then it will work.

    Please select your storyboard file