Determine the size of a View by inspecting its NIB

I was exploring the UICollectionView API tonight and stumbled upon an old problem. Both UITableView and UICollectionView ask their delegate for size information about the cells they display. When creating cells in separate XIB files, which I normally do, this means that the delegate must somehow know how big the root View is in that XIB. The easiest way to do that is evil: hard-code the cell’s size in the delegate. Duplication! Yuck!! No more!!!

It dawned on me that this entire problem can be avoided by doing a one-time lookup of the View’s natural size, as it exists in the XIB file (and, at run-time, in the view’s NIB). I posted a Gist on GitHub that shows my simple solution:

Happy coding!

About Josh Smith

Josh Smith is a musician at heart, and a software developer by obsession. He lives in Arizona, plays classical music on the piano, jazz on the guitar, and enjoys brutally long rides on his bicycle. He has a wonderful wife and thinks that, in general, life is good.
This entry was posted in Interface Builder, Tips and Tricks, UICollectionView, UITableView. Bookmark the permalink.