Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView with variable cell sizes

I'm struggling a little bit with the size for cells in UICollectionView. In android, you can easily "wrap" the size of the cell. Just like in iOS, you have a function call 'GetCell' and you decide how big it will be.

The difference in iOS is that in the "getCell" function (of UICollectionViewController) it seems you can't choose the size of the cell (or the contentview). If I change the size, it will ignore it and use anyway the general 'ItemSize' of the CollectionView (which is the same for all cells).

This sometimes results in Views which are not very beautiful. For example, if I have a horizontal list with images, I want the distance between images to be the same, independent if one image is 200x200 and the other 400x200. So the cell size should be different also.

It is possible to define a different size for different cells. You can use the Collectionview delegate and the GetSizeForItem (= sizeForItemAtIndexPath in ObjC) function. The problem is, this function is called BEFORE the actual GetCell function.

So if I have a more complex Cell, with for example some labels. In my "GetCell" function, I build this Cell and at the end, when returning the Cell, I know which size it should be. However, in the GetSizeForItem function, that info is not available yet, because the Cell is still 'null'.

The only way I could do it, is to actually build the UIView for the cell (so I can request the size) at the moment of the 'GetSizeForItem' call. But this doesn't seem a good design, because I'm building the UIView before the 'GetCell' where I will build it again.

Is there something I'm overlooking?

Regards, Matt

like image 731
Matt Avatar asked Nov 23 '12 15:11

Matt


1 Answers

Indeed GetSizeForItem gets called separately from GetCell. It's done that way because creating UIViews is a very time and memory consuming task, and your application would either run out of memory or have to dispose other views to be able to handle big lists.

Before the view gets presented, the UICollectionView (and UITableView) asks for the sizes and positions of all (or most) elements in the list, so it can know where to draw them. Many of those elements won't be visible though, so the collectionView avoids having to create them. This is why the GetSizeForItem gets called upfront, and the GetCell only later.

In your case, try to separate the logic that calculates the size of the view from the view itself. Make it a simple math formula that doesn't require a view to exist, so it's fast enough to be run upfront.

like image 55
Eduardo Scoz Avatar answered Sep 28 '22 14:09

Eduardo Scoz