Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell - Best place to set up the cell

I've been playing around with custom cells in a UITableViewController by have a base cell (BaseCell - subclass of UITableViewCell) and then subclasses of BaseCell (Sub1Cell, Sub2Cell, both subclasses of BaseCell).

Because the subclasses share some of the same features, if I set them up completely in

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

I start to repeat code for each cell type. Is there a good place, and is it good practice, to put generic set up code inside the actual custom UITableViewCell class? Currently I've written a simple setup method:

- (void)setupCell
{
    self.picture.layer.cornerRadius = 5.0f;
    self.picture.layer.masksToBounds = YES;
    self.picture.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.picture.layer.borderWidth = 1.0f;
}

I've just been calling this once I create my cell:

Sub1Cell *cell = [tableView dequeueReusableCellWithIdentifier:statusCellIdentifier];
[cell setupCell];

Is there a method I can use that will be called automatically? I tried -(void) prepareForReuse but it, obviously, isn't called every time, and only when cells are being reused.

Any advice on the best way to go about this?

Edit:

It seems is actually being called every time I call tableView:cellForRowAtIndexPath. I was a bit confused with the correct way to create a custom cell. Should I be doing something along the lines of:

Sub1Cell *cell = [tableview dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
    cell = [[Sub1Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    [cell setupCell];
}

If I don't do anything with the style passed, will it affect my custom cell?

like image 672
Christopher Oldfield Avatar asked Feb 27 '12 05:02

Christopher Oldfield


2 Answers

You can use awakeFromNib in your cell subclasses. This will be called when a new cell is created from the prototype in your storyboard, but not when a cell is re-used.

If you are using prototypes then the whole if (cell == nil) thing goes away, UITableView handles all that for you within the dequeue method.

like image 85
jrturton Avatar answered Oct 21 '22 06:10

jrturton


In the custom cell class, provide a init method, to initialize. some codes like below:

- (id)initWithReuseIdentifier:(NSString *)cellIdentifier
{
    if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier])
    {
        self.picture.layer.cornerRadius = 5.0f;
        self.picture.layer.masksToBounds = YES;
        self.picture.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        self.picture.layer.borderWidth = 1.0f;
    }
    return self;
}
like image 43
Wubao Li Avatar answered Oct 21 '22 05:10

Wubao Li