views:

618

answers:

1

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;

}

+1  A: 

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.

iKenndac
Yes I had tried that but I got the runtime error:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UIView setText:]: unrecognized selector sent to instance 0xf4a0c0'How come it recorgnizes it as a UIView not a UILabel...?
SimpleCode
Ah, in that case you're not getting your original instance back — what's the `messageTag` value set to? If it duplicates another view's tag (for example, all view's tags are zero unless you change them), you'll get the wrong view back.
iKenndac
U know Ken, I set the messageTag to be 0 and that caused my trouble. I changed it to a random number 342343 and it works!!!! Yeehaaa!!! This problem wasted me so much time until you answered me Ken. Thanks so much! Can I buy you a drink or something :)"for example, all view's tags are zero unless you change them" very valuable info! Thanks Ken!
SimpleCode