【问题标题】:TableViewCell's textLabel value returns to 1 when cell is scrolled out of the view当单元格滚动出视图时,TableViewCell 的 textLabel 值返回 1
【发布时间】:2012-01-11 04:33:55
【问题描述】:

我有一个表格视图,我可以在其中将我的 cell.textLabel.text 的值加 1 或减 1,但是当我切换视图并返回或滚动一个单元格时,当它返回到视图中时, textLabel 的值返回到 1 原来的起点!请帮忙!下面是加减1的代码:

 - (IBAction)addLabelText:(id)sender{

    cell = (UITableViewCell*)[sender superview]; // <-- ADD THIS LINE

        cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text  
                                                                intValue] +1];

}


- (IBAction)subtractLabelText:(id)sender
{
   cell = (UITableViewCell *)[sender superview];        
    if ( [[cell.textLabel text] intValue] == 0){ 
        cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] +0];
    }
    else{
        cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] -1];
    }
}

【问题讨论】:

    标签: iphone ios ipad uitableview ipod


    【解决方案1】:

    发生这种情况是因为单元格将在滚动时重复使用。将调用表视图的数据源方法,因此值将重置为原始值。您可以维护一个NSNumbers 数组作为tableview 的数据源(在cellForRowAtIndexpath: 中,从数组中设置单元格标签的文本)。每次需要加减时,做对应的NSNumberobj,重新加载tableview。

    【讨论】:

    • 好的,我想我明白你在说什么。我想我对我的 tableView 图像做同样的事情。我的cellForRow 方法中有这段代码:cell.imageView.image = [imageArray objectAtIndex:indexPath.row]; 这就是你在说的吗?我只需要将其更改为 NSNumber?非常感谢您的帮助!
    【解决方案2】:

    似乎您每次都在分配一个新单元格..而不是使用单元格重用方法。 在您的情况下,当您对先前的值执行算术运算并且您没有数组来存储先前的值时。解决此问题的最简单方法是使您的 Cell-Identifier 独一无二。 (类似于@"Cell-%d",indexPAth.row)

    注意:但是,更有效的方法是将结果保存在要从中填充数据的数组中,而不会使 Cell-Identifier 唯一。

    【讨论】:

    • 好的,我采纳了你的建议并添加了这个:- (IBAction)addLabelText:(id)sender{ cell = (UITableViewCell*)[sender superview]; num = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] +1]; [number addObject:num]; [myTableView reloadData]; } 这可以吗?它加得很好,但我不能让它减去和工作!感谢您的帮助 +1
    • 不!您的初始代码(即您问题中的代码)将起作用。假设您已使单元标识符唯一,只需在两个方法的末尾添加 [myTableView reloadData] 即可。它应该工作。祝你好运。
    【解决方案3】:

    您没有更新数据模式。这就是它采用原始内容值的原因。

    【讨论】:

    • 首先,谢谢你的帮助,其次我不太清楚什么是模态,所以你能解释一下吗?再次感谢
    【解决方案4】:

    更改单元格文本值后重新加载表格视图[self.tableview reloadData]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多