Reputation: 6829
I have UITableViewController. In cellForRowAtIndexPath
method I added custom setup for label:
UILabel *lblMainLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 9, 150, 25)];
lblMainLabel.text = c.Name;
lblMainLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
lblMainLabel.backgroundColor = [UIColor clearColor];
lblMainLabel.textColor = [UIColor whiteColor];
[cell.contentView addSubview:lblMainLabel];
[lblMainLabel release];
But when I scroll UP or DOWN in table it always add this label on top of previous what I miss?
Upvotes: 2
Views: 5210
Reputation: 864
Yes fluchtpunkt, you are right. cellForRowAtIndexPath gets fired every times the tableview scrolls, it will reloads the data.
if (cell == nil)
{
}
will get fired once the cell is allocating. else memory also gets increased.
Upvotes: 0
Reputation: 90117
you should create the UILabel exactly one time, when you create the cell.
Your code should look like this:
if (cell == nil) {
cell = ...
UILabel *lblMainLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 9, 150, 25)];
lblMainLabel.tag = 42;
lblMainLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
lblMainLabel.backgroundColor = [UIColor clearColor];
lblMainLabel.textColor = [UIColor whiteColor];
[cell.contentView addSubview:lblMainLabel];
[lblMainLabel release];
}
UILabel *lblMainLabel = [cell viewWithTag:42];
lblMainLabel.text = c.Name;
Upvotes: 14