RoundOutTooSoon
RoundOutTooSoon

Reputation: 9891

iphone sdk: Can't reuse cell with viewWithTag (can not setText to reused labels)

This is my cellForRowAtIndexPath function. I could not get the setText to the label to work. Can you please help me out?

// Customize the appearance of table view cells.

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

    static NSString *CellIdentifier = @"Cell";
    UILabel *messageLabel = nil;
    int row = [indexPath row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, ROWHEIGHT) reuseIdentifier:CellIdentifier];
        messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 240, 60)];
        [messageLabel setFont:[UIFont fontWithName:@"ArialMT" size:12]];
        [messageLabel setTextColor:[UIColor blackColor]];
        [messageLabel setBackgroundColor:[UIColor clearColor]];
        [messageLabel setNumberOfLines:3];
        [messageLabel setLineBreakMode:UILineBreakModeWordWrap];
        [messageLabel setTag: messageTag];

        [cell.contentView addSubview:messageLabel];

    }
    else{
        messageLabel = (UILabel *)[cell viewWithTag:messageTag];

    }

    [messageLabel setText:[[[aSingleton wallItemArray] objectAtIndex:row] message]];

    NSLog(@" -- > at row %d, message: %@", row, [[[aSingleton wallItemArray] objectAtIndex:row] message]);

    return cell;
}

Upvotes: 0

Views: 3716

Answers (1)

iKenndac
iKenndac

Reputation: 18776

You're adding the UILabel to the cell's contentView, but asking the cell for the view.

Have you tried:

messageLabel = (UILabel *)[cell.contentView viewWithTag:messageTag];

EDIT: Also, you have two memory leaks - you're alloc'ing a UITableViewCell and a UILabel without (auto)releasing them anywhere.

Upvotes: 2

Related Questions