Iphone UITableViewCell中的自定义标签存在问题
我有一个UITableViewController。在Iphone UITableViewCell中的自定义标签存在问题,iphone,objective-c,uitableview,uilabel,Iphone,Objective C,Uitableview,Uilabel,我有一个UITableViewController。在cellforrowatinexpath方法中,我添加了标签的自定义设置: UILabel *lblMainLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 9, 150, 25)]; lblMainLabel.text = c.Name; lblMainLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20
cellforrowatinexpath
方法中,我添加了标签的自定义设置:
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];
但当我在表格中向上或向下滚动时,它总是将此标签添加到前面我错过的内容之上。创建单元格时,您应该只创建一次UILabel 您的代码应该如下所示:
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;
是的,你是对的。 cellForRowAtIndexPath在每次tableview滚动时被激发,它将重新加载数据
if (cell == nil)
{
}
将在单元分配时被激发。否则内存也会增加 如果你同意一个答案,请投上一票,也许再加上一条评论。这不是一个真正的“答案”。为什么标签应该是42号?或者这真的不重要吗?标签当然是一个任意数字。但是,在指定标记和检索带有标记的视图时,必须使用相同的编号。