Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating UITableViewCells programmatically

My UITableViewCells are getting a bit out of hand and I'm trying to structure them better. The issue is that the cells can have different layout structures such as number of labels, label widths and position, and can include different images and buttons. In order to perform the layout only once, I have created custom NIBs for each configuration, but this has resulted to over 20 different possible layouts which are hard to maintain and adjust.

I'm considering programmatic creation of the cells (avoiding storyboard prototypes and NIBs altogether) and was hoping to understand if this is a common practice and if there are performance tradeoffs I should be aware of.

What are your general suggestions in solving such an structure?

like image 974
x89a10 Avatar asked Mar 17 '26 13:03

x89a10


2 Answers

Creating UITableViewCells through the code should neither give your advantages nor disadvantages compared to creating them through NIBs or by using multiple prototype cells. NIB files and prototype cells let you manipulate cell layout visually, but they do not prohibit you from additionally manipulating it in your program.

All three ways of building the cells have one common requirement - the cells of different kind must have different reuse identifiers (see this question for a discussion).

If it is the proliferation of the 20+ NIB files that you are worried about, consider the prototype cell approach, which lets you stay within a single storyboard file.

like image 152
Sergey Kalinichenko Avatar answered Mar 20 '26 05:03

Sergey Kalinichenko


the way that I would solve that sort of problem is indeed switching to programmatic creation because then you can do subclass and implement and same functionality throughout your xibs only once. For instance lets say you have a cell that needs to have a square inside it colored red and sometimes you need another square colored green inside the red square. Well you can have a base class of MiddleSquareCell and then subclass it with GreenSquareCell which just has an override for painting the green square. Another advantage to programmatic solutions is configuration options. So for instance you could have a class SquareCell and then have a configuration option when you create it that says

[squareCell setRedSquareVisible]; 

Or

[squareCell setRedSquareVisible]; 
[squareCell setGreenSquareVisible]; 

Things like that. Anyways this is a way to implement it. I hope this helps.

like image 41
Tony Avatar answered Mar 20 '26 06:03

Tony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!