Table view with custom cell (programmatically)

gotye picture gotye · Mar 27, 2010 · Viewed 24.1k times · Source

So far, I used to create custom nibs to make my cell as I wanted but this time, the height of a cell will change from one to another so that I can't create a fixed-size cell's nib.

So I decided to create it programmatically ... Is the way below the good way to achieve it ?

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        UILabel *pseudoAndDate = [[UILabel alloc] initWithFrame:CGRectMake(0.0,0.0,320.0,20.0)];
        [pseudoAndDate setTag:1];
        [cell addSubview:pseudoAndDate];
        [pseudoAndDate release];
    }

    CommentRecord *thisRecord = [comments objectAtIndex:[indexPath row]];

    UILabel *label = (UILabel *)[cell viewWithTag:1];
    [label setText:[NSString stringWithFormat:@"%@ | %@",thisRecord.author,thisRecord.date]];

    return cell;
}

or .. am i missing something here ? Cause so far it doesn't seem to work ;)

Thanks,

Gotye.

Answer

Nate Symer picture Nate Symer · Aug 11, 2013

Why create a label when you don't need to? Use the UITableViewCell's label.

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    CommentRecord *thisRecord = [comments objectAtIndex:[indexPath row]];

    cell.textLabel.text = [NSString stringWithFormat:@"%@ | %@",thisRecord.author,thisRecord.date];

    return cell;
}