customtablecell

Custom UITableViewCell – Not Quite As Daunting As I’d Thought…

I’ve previously hit on the need to use a custom UITableViewCell, though I’ve always shied away from it because of project time constraints and the assumption that it would take some sweet time to perfect.

Well… as it turns out I was wrong.

It’s easy!

Create in X-Code

If you create a new file in X-Code and choose to make the file a subclass of UITableViewCell, it’ll set everything up as you need for you:

Set up MyCustomCell

Set up MyCustomCell

You’ll be faced with this code:

Implementation

Interface

Okay, so it’s quite easy to customise the cell, but to do that you’ll need to understand how a cell is initially composed.
In a standard cell there is a single UILabel called textLabel, in a detail cell, there are two, textLabel and detailTextLabel.

In my particular example, I need three. One as the primary (like the normal textLabel), one as the secondary (emulating the detailTextLabel of the UITableViewCellStyleSubtitle), and one over to the right hand side (emulating the UITableViewCellStyleValue1 detailTextLabel).

MyCustomCell Layout

MyCustomCell Layout

Creating my Labels

We’re not restricted to labels, by any means. This is just the method I needed to employ to create this. We can use most other components too, such as UIImageView.

Here are my three labels in the header file set up as standard:

Now I need to define their properties in my implementation:

You can define any label properties at this stage, but don’t touch positioning just yet, we’ll modify that through another method.
You can adjust the text colour, background color, font, font weight and font alignment etc. Anything that affects the label itself.

We need to create a method now to handle the positioning of the labels:

As you can see we create a frame with CGRectMake and then apply it to each of the labels, adjusting as necessary.

Your custom cell is created and ready to be shown to the world!

Adding to a TableView

Firstly, I need to import the class to where I would like to use it. I had an existing tableView set up.
All the adjustments you need to make will be in the cellForRowAtIndexPath method on your tableView:

Firstly, I need to adjust my cell definition, to ensure it reads from my subclass as opposed to the default:

Now that’s done, I’ll have access to set my labels:

Here’s the full method.

That’s it.

Create a subclass, define it’s parts, position it’s parts and switch the cell type.

I feel immediately more confident to experiment with this concept now.

Comments

comments

Powered by Facebook Comments