StuartM
StuartM

Reputation: 6813

Setting up a UITableViewCell subclass in code

I am reading the apple docs on setting up custom subclasses of UITableViewCell - Docs

In this example I need to setup a custom cell which does not have a NIB/storyboard file. The apple docs provide an example of using a predefined style and configuring that but not creating a completely custom layout.

  1. How should the cell be called in.. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath ?

I am looking to have a completely custom layout so is this correct? As the cell is being called initWithStyle...?

MESLeftMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if(cell == nil)  {
    cell = [[MESLeftMenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
  1. In the custom cell subclass how/where should I implement the setup of the views within the contentView? Which method is called for the init, would it be initWithStyle as above? If so, can I simply create the cell outlets in there once only?

Then in the cellForRowAtIndexPath can I access the outlets as i.e. cell.MainLabel.text ... ?

Upvotes: 0

Views: 1792

Answers (2)

DogCoffee
DogCoffee

Reputation: 19946

This is how I have been shown to set up my Collection View Cells in their custom class. I know you are using a tableview but this is threw me for a while so decided to add here. Hopefully it helps you.

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    [self commonInit];
}
return self;
}

- (id)initWithCoder:(NSCoder *)encoder
{
    self = [super initWithCoder:encoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    // set up your instance
}

To access the outlets of that cell I just add outlets to the header file of the custom class and you can easily access them.

Upvotes: 1

Sorin Cioban
Sorin Cioban

Reputation: 2225

As of iOS 6, you no longer need to check whether the dequeued cell is nil.

What you would do is as follows:

In the viewDidLoad method of the view controller containing the table view you could say

[self.tableView registerClass:[MyCellClass class] forCellReuseIdentifier:MyCellIdentifier];

This results in your dequeueReusablecellWithIdentifier call to never return nil. In essence, in the background, initWithStyle is called. So you would set your stuff up when overriding that function.

Upvotes: 0

Related Questions