Problem with custom label in UITableViewCell

本小妞迷上赌 提交于 2019-12-07 17:33:29

问题


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?


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/4967554/problem-with-custom-label-in-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!