Dynamic itemSize based on Screen Orientation

Subscribe to my newsletter and never miss my upcoming articles

Hello my people, Leo Here.

Today I'll show you how to set a dynamic size of a UICollectionViewCell.

It's simple but require a little bit of lifecycle understanding. You will manipule the willTransition method inside your UIViewController to achieve that.

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 always 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.

Thanks for the reading and... That's all folks!

No Comments Yet