Dynamic UICollectionViewCell size and Device Orientation

Hello my people, Leo Here. Today I’ll show you how to set a dynamic size of a UICollectionViewCell based on device orientation.

It’s simple but requires a little bit of lifecycle understanding. To achieve that, you will manipulate the *willTransition* method inside your UIViewController.

Using UICollectionViewCells can be very easy and intuitive, but things begin to get troubled when you have to give support to multiple orientations. Theoretically, UICollectionView should handle everything for you, and it does, but mind that when you turn your phone around not always the size of the UICollectionViewCells greatly fits in the new screen configuration.

It is always important to visually check the changes

How to set a dynamic size of a UICollectionViewCell?

Let’s code:

Imagine that you want your cells to be 29% of the screen’s width, in portrait or landscape mode. A Trello-like app would appreciate this kind of feature because your cards will continually expand/respond to the device orientation.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

super.viewWillTransition(to: size, with: coordinator)
guard let kanbanView = view as? KanbanView,
let todoLayout = kanbanView.todoCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
else { return} // here we are getting the UICollectionViewFlowLayout from the view.


let newSize = CGSize(width: size.width * 0.29, height: 160) // here the magic happens
todoLayout.itemSize = newSize // set the new size
todoLayout.invalidateLayout() // it's important to call invalidateLayout to redraw the collection view
}

This way the width of your will change dynamically based on how the screen state will be.

Summary

Today we learned how to dynamically set the size of a UICollectionViewCell and how that can improve your code base.

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits: image

Share this post:

Related posts

Sponsor