UITableViewCell 中自定义标签的问题

发布于 2024-10-17 11:10:53 字数 518 浏览 4 评论 0原文

我有 UITableViewController。在 cellForRowAtIndexPath 方法中,我添加了标签的自定义设置:

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];

但是当我在表格中向上或向下滚动时,它总是将此标签添加到我之前错过的内容之上?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

没企图 2024-10-24 11:10:53

您应该在创建单元格时创建 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;

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;
吻安 2024-10-24 11:10:53

是的,fluchtpunkt,你是对的。
每次 tableview 滚动时,cellForRowAtIndexPath 都会被触发,它将重新加载数据。

if (cell == nil)
{

}

一旦单元格分配就会被解雇。否则内存也会增加。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文