Rahul Ahuja
Rahul Ahuja

Reputation: 765

iOS Dynamic cell content

I have searched for this a lot and haven't found what I am looking for.

I want to have UITableViewCell such that each have dynamic content. For example, one cell can have a place name, address, phone number, image, etc. Another cell can have some or all of these attributes.

enter image description here

I know that I should have functions cellForRowAtIndexPath: and heightForRowAtIndexPath: return stuff appropriately.

The problem I am facing is that I have my cells designed in nib files, and am loading the layout from there. I can calculate the heights for each cell based on conditions(though this is tedious), also I need to arrange stuff in that cell if one thing is missing. For example, if place name is missing then move all the elements up via setFrame:.

There should be an easy way out I believe?

Upvotes: 1

Views: 466

Answers (1)

Matic Oblak
Matic Oblak

Reputation: 16794

In such dynamic cases I would not bother with using storyboards to accomplish this. It should be very easy to do this programatically...

If you really do need to create this in a storyboard you could generate a full cell which could consist of (for instance) 5 labels. Now in the table view data source I presume you have some array of objects where each element represents a single row in the table view. If so then in your case each of this object can have a method that will return an array of non-empty strings (the strings that will actually be displayed) which can be a dynamical count from 1 up to 5 strings.

If you do this you will request this array in method requesting the height for row at index path and by using this count you can then return the height of the row (for instance numOfStrings*40.0f). Inside the method requesting your cell you can simply fill those labels with the same array you use to calculate the height.

As for non storyboard approach I suggest you to override an UITableViewCell, generate a static method that will return you the cell height for string count and generate an initializer with the string array which should then iterate through the array generating the labels and setting the text to it.

Upvotes: 2

Related Questions