I want to display different UITableViewCells depending on what content is available . How can I accomplish that ?
Example:
Lets say I have a custom UITableViewCell whose contentView has a UILabel, UITextField and a UIImageView as subviews. The UILabel is located on the top of the cell, above the UIImageView which is next to the UITextField. Depending on which contents for these views is available, I would like to only display the available parts and enlarge the other views. e.G: If there is missing the UILabel context I don’t want to have a blank space at the top of the cell. If I don’t have an image, the text field should start at the very left side of the cell.
There should be many newspaper/tv applications out there which had to solved exact the same problem…
Approaches:
(i) Using the same custom cell where I somehow rearrange the subviews
(ii) Calling different custom UITableViewCell‘s depending on what content is available
For both approaches I am having issues finding a path to solve this problem. My UITableView content size is dynamic and can have a few rows or many.
Is there any other approach I am missing out or if not which approach is best practice?
Either approach works, although I would probably prefer (i).
For (i), reuse is easy. Just make sure you clear out the old data when reusing, have your UITableViewCell’s
layoutSubviewsmethod lay the subviews out appropriately to match whatever data is available, and be sure to callsetNeedsLayoutwhen you change the data. The advantage here is that the rest of your code doesn’t need to care about which data is available or not, and your table may not even have to care if the cell suddenly gets an image added (unless it needs to know that the cell height changed or something). The disadvantage is that the cell’s implementation is more complex, and the layout cannot be completely defined in IB.For (ii), each different custom UITableViewCell type must have its own
reuseIdentifier, and then usedequeueReusableCellWithIdentifier:with the identifier appropriate to the available data. The advantage here is that the individual cell types are simpler (and can probably be done entirely in IB), while the disadvantage is that you have to have several of them for each possible combination of available data. Also, you would need to have the UITableView reload the cell (e.g. usingreloadRowsAtIndexPaths:withRowAnimation:) if the type needs to change.