Custom Label Problem in UITableViewCell

I have a UITableViewController. In the method, cellForRowAtIndexPathI added a custom setting for the 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 a table, always add this label on top of the previous one, what did I miss?

+3
source share
2 answers

You must create the UILabel exactly once 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;
+15
source

Yes, fluchtpunkt, you're right. cellForRowAtIndexPath is launched every time the tables are scrolled, it reloads the data.

if (cell == nil)
{

}

will be launched after the selection of the cell. otherwise, memory also increases.

+1
source

Source: https://habr.com/ru/post/1791436/


All Articles