Making Life Easier Since 2012™
One of the great things about Cocoa / iOS development is also one of its downsides: you don’t need to know exactly what’s going on behind the scenes. Judging from some of the questions that come up on StackOverflow with surprising regularity, a sizeable number of users don’t realise that a
UITableView is actually recycling views and cells to conserve memory.
This introduces a lot of problems when developers come to implementing things like galleries. Almost every other day there’s a question along the lines of “I put ten images into a scroll view and my phone crashed, what’s going on?”. Inevitably it’s down to memory simply running out. Until iOS 6 you were faced with several far from ideal options to fix this: write your own recycling system, use one of several open-source options (of varying quality), or hack a
UITableView to pieces.
Collection views change that, in a good way. Some people describe them as “gallery views”, but that’s actually not the case -
UICollectionView goes deeper than that. Unlike a table view, the display logic (how your items are laid out on the screen) is totally decoupled from the recycling logic. A collection view is paired up with a layout class that describes where and how elements should be positioned.
The most common layout - a gallery - is provided through the built-in
UICollectionViewFlowLayout class, but by substituting your own layouts you are free to display your items however you want: cover flow, 3D-like layouts, circular layouts, pile layouts (à la Mail) - they’re all easily achieved by switching out the layout class.
There is, of course, a downside to all these benefits: collection views are only available on iOS 6. To be honest, for many people this shouldn’t be a problem. Some of the apps I work on show over 80% of users running iOS 6, and that’s only two months after it was released.
However, there’s good news for those looking to implement flow and gallery layouts - Peter Steinberger has put together a great drop-in replacement class for iOS 4.3-5 that has a 100% compatible collection view API.
Stop Writing Custom Galleries
The upshot of this is it would be absolutely crazy to implement your own recycling gallery view from scratch, even if you have to sub-class a collection view or write your own layout to get the effect you want. Setting aside the fact that in the vast majority of cases using a collection view will save development cost and time, you’re also backed by code that’s received far more testing time than your custom written class ever will.
The take away lesson: collection views are a fantastic addition to iOS, and you should be using them wherever possible in your apps rather than custom or third-party code. Learn to love them, and you will be rewarded.