【问题标题】:Problem with custom label in UITableViewCellUITableViewCell 中的自定义标签问题
【发布时间】:2011-02-11 09:45:05
【问题描述】:

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

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

【问题讨论】:

    标签: iphone objective-c uitableview uilabel


    【解决方案1】:

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

    【讨论】:

    • 为什么标签应该是数字42?还是真的不重要?
    • 标签当然是任意数字。但是在分配标签和检索带有标签的视图时,您必须使用相同的编号。
    【解决方案2】:

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

    if (cell == nil)
    {
    
    }
    

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

    【讨论】:

    • 如果您同意某个答案,请点赞,或许还可以添加评论。这并不是真正的“答案”。
    猜你喜欢
    • 2011-07-17
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    相关资源
    最近更新 更多