iOS8 Weirdness Part3: Laggy UICollectionView

Autolayouts, something that people love and hate. When Apple introduced them i had mixed felling about it, from one hand it reduces tons of code, also do a lot of calculation for you and of course it magically works! In other hand… it is terribly slow i still see my manual setFrame: at least 10 times faster than calculation something in AL but nothing for free.

This post will not be long, the main problem is that as most of you may know using autolayout in scrollview is pain in ass terrible slow due to continous autolayout recalculation mostly if you use xib loaded view with AL attached to them. So why not to use UICollectionView better, faster, bigger, stronger. I have heavy collection view with very complicated cells (in terms of autolayout) but they are done pretty smart and work really fast and smooth, of course only in iOS7

After updating my ipad to iOS8 i encounter terrible lags while scrolling UICollectionView in my app. Again instruments bug haunting with tons of coffee shows me that my amazing UICollectionView starts acting exacly like ugly UIScrollView solution and recalculates cells autolayout over and over again!

Gladly solution to that is pretty simple. If you watched WWDC 2014 about changes in collection view you propably noticed that Apple introduces some new Invaidation Context etc. But we do not need to implement all of that if you want to get your smooth and nice scrolling the only thing you need is to implement this method in your custom UICollectionViewCell

1
2
3
4
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    return layoutAttributes;
}

And you are done! Collection view again works as expected, it happens because this is called before autolayout calcualtion and it returns proper cell size so there is no need to trigger recalcualtion again. You should see some visual changes eg collection view cell will no more weirdly rescale from 1x1 to it desired scale.

That’s all for now, next time some UIButton good practices for those who just start coding in iOS and want their flat buttons looks and works good.