swiftuicollectionviewuicollectionviewcelluicollectionviewlayoutaspect-ratio

Adapt size of items layout in CollectionView according to screensize maintaining the aspect ratio


I'm trying to adapt the size of items in a CollectionView to the screensize maintaining the aspect ratio. Untill now it works well only on iPad, I've setted an height and a width, according to the dimensions of the assets:

private let cardWidth: CGFloat = 362
private let cardHeight: CGFloat = 568

Then in CardLayout class, which inherits from UICollectionViewFlowDelegate:

   scrollDirection = UICollectionViewScrollDirection.Horizontal
   itemSize = CGSizeMake(cardWidth, cardHeight)
   minimumInteritemSpacing = 10

Problem is that items are cards, so height > width, while I'm developing for both iPhone and iPad in landscape only. I've tried to use UIScreen.mainScreen().bounds without success. I managed to get a decent result for both iPhone and iPad adding in CollectionViewController:

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

return CGSizeMake(collectionView.frame.size.height / 2 ,collectionView.frame.size.width / 2)
}

where I swapped width and height when returning a size, since the app is landscape only. Still this is not the best solution, since cards does not maintain the aspect ratio. So is there a way to adapt size to screen maintaining the aspect ratio?


Solution

  • You can apply aspect ratio constraints to the cells so that they themselves maintain aspect ratio, and then apply another constraint from the cells to the view so that they maintain aspect ratio in relation to the view. You can then apply an equal widths/height constraint to adjust the size of the cells through a multiplier.