0
votes

I'm trying to build a collection view (Xcode 8, Swift 3) which shows two cells per row. Every cell in the collection view has (top to bottom):

  • An ImageView
  • A Title label
  • A Subtitle label

I have set up the cell in storyboard as follows:

  • Cell Size: 250 x 258
  • ImageView pinned to the container cell (0 top, 0 leading and 0 trailing) pinned to the Title label (10 bottom)
  • Title label pinned to the container cell (12 leading, 12 trailing) and to the subtitle label (-0.5 bottom)
  • Subtitle label pinned to the container cell (12 leading, 12 trailing, 0 bottom)
  • Section insets 10 all around
  • Min spacing 10 for lines

Then in my controller's viewDidLoad I set the following:

let width = collectionView!.frame.width / 2
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: width - 15, height: width - 4)

When I run the app, apparently everything looks fine. However if I start scrolling up and down or change to a different tab and return, some of the images appear taller than they should (the cell remains the same size for every item but the image is taller and pushes the label beneath).

I'm assuming this is an issue with autolayout but I'm not sure how to make it so that the collection view shows two cells per row while keeping the image within the cells at the same ratio (images are rectangular 250 x 197). I can't set fixed width and height values for the image because I need it to scale proportionally depending on screen size.

I have looked online for solutions but most collection view tutorials work with square images where the same value is set for width and height so they don't go into how to maintain proportions in rectangular images.

1
Have you ticked "clips to bounds" in the image view?Fogmeister
Yes, unfortunately that doesn't solve it. Also it happens at random and all images are the same size.cesarcarlos
Since you do not want to set the width and height statically, you could set it's aspect ratio to be 1:27 to keep your images at the same as 250x197Jacob Boyd
Have you set an aspect ratio constraint on the image view? If it's always a fixed aspect ratio then you can add that too.Fogmeister
The aspect ratio constraint seems to have done the trick. Thanks!cesarcarlos

1 Answers

0
votes

Just so the question can be marked as answered!:)

"Since you do not want to set the width and height statically, you could set it's aspect ratio to be 1:27 to keep your images at the same aspect as 250x197"