Search code examples
swiftuicollectionviewtvos

UICollectionView equal cell spacing


I am displaying several images in a collection view. They are all the same orientation (landscape) except for one, which is portrait (see image below):

enter image description here

I am trying to make the portrait image more centered, so that everything is evenly spaced. Any ideas on how to do this?

PhotoGalleryViewController.swift:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoGalleryCell

    let image = UIImage(named: images[indexPath.row])
    cell.imageView.image = image
    cell.captionLabel.text = captions[indexPath.row]
    return cell
}

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    var size = CGSize()

    if (indexPath.row == 3)
    {
        size = CGSize(width: 450, height: 600)
    }
    else {
        size = CGSize(width: 940, height: 600)

    }
    return size
}

Solution

  • My suggestion would be not altering the cell size based on the fact that a portrait image will be in item 3.

    Instead update the layout of your cell so that whatever image it gets assigned to it's image view, it will centre the image in itself and centralise the label underneath the image.