Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection View With Fixed Number of Rows and Columns

I have a collection view and would like to maintain a consistent number of rows and columns across multiple devices. On an iPhone 6s Plus, 6 items are displayed, but when viewing the app on an iPhone 5s, only four items are displayed.

See my layout here: Layout on iPhone 6s Plus

How can I make the collection view display the same items on various devices?

like image 999
iOS Ninja Avatar asked Oct 22 '25 07:10

iOS Ninja


1 Answers

For Swift 3.0.

Ensure you are using autoLayout and implement the UICollectionView sizeForItemAtIndexPath.

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

        return CGSize(width: collectionView.bounds.size.width/3 - yourCellInterItemSpacing, height: collectionView.bounds.size.height/3 - yourCellInterItemSpacing)
  }

This will allow your cell to be created based on the screen size (Assuming you are using autoLayout), you should divide by the number of columns/rows you want. Divide width by the number of columns you want and height by number of rows.

To provide leading and trailing spaces as seen in your screenshot, just add appropriate spaces in the storyboard to your UICollectionView. I.e Leading and trailing spaces equivalent to yourCellInterItemSpacing

Make sure your class conforms to the UICollectionViewDelegateFlowLayout protocol!

like image 98
Rikh Avatar answered Oct 25 '25 07:10

Rikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!