bandejapaisa
bandejapaisa

Reputation: 26992

Create UITableViewCell from nib, dynamic cell height

I create most of my UITableView cells from nibs. On this particular project there is a lot and they are of a variety of sizes.

Now I specify my cell height in my nib when I'm designing it, and I want this to be the only place I specify this value.

However, tableView:heightForRowAtIndexPath:, is called before my nib is loaded in cellForRowAtIndexPath, so I don't have the value.

This is 'mildly' annoying, as I have to specify my height again in the code.

I could preload a nib beforehand to get this value. Has anyone got any clever patterns they use to manage this, or do you just live with it?

Upvotes: 1

Views: 823

Answers (2)

David Hoerl
David Hoerl

Reputation: 41682

Well, I can think of three ways to make this a bit easier:

1) encode the height into the nib name - myNib.47.xib

2) Create a mutable dictionary, and at viewDidLoad create entries for the reuseIdentifier as the key and a nsnumber as the object.

3) Variation on 2. At viewDidLoad, associate UINib objects with the reuseIdentifier using:

cellNib = [UINib nibWithNibName:@"MyCellNibXYZ" bundle:nil];

in a mutable dictionary. When you need a cell, you call:

UINib *nib = [mutableDictioanary objectForKey:...];
MyCell *cell = [[cellNib instantiateWithOwner:nil options:nil] objectAtIndex:0];

You can then instantiate a cell when you need the height, then toss it. The instantiate is a lot faster than going to the file system to read the file on each access.

Upvotes: 2

holex
holex

Reputation: 24041

you've written: Now I specify my cell height in my nib when I'm designing it, and I want this to be the only place I specify this value.

if you really want to keep the height only in the IB, you should create an instance of every cell from Nib in your -init: or -loadView method and you can use that instances to determine what the final height of the cell is. therefore, you will know the exact height for each of your cells, using these pre-inited instances, in the - tableView:heightForRowAtIndexPath: method then.

not too elegant but it is working.

Upvotes: 0

Related Questions