Iphone self.tableView reloadData将文本堆叠在单元格标签中,而不是首先清理它

Iphone self.tableView reloadData将文本堆叠在单元格标签中,而不是首先清理它,iphone,ios,objective-c,xcode,ipad,Iphone,Ios,Objective C,Xcode,Ipad,在用户从上一个屏幕中选择一个值,导航控制器弹出该值后,我试图更新单元格内的标签(注意,这不是单元格的标签文本。它是单元格内的另一个自定义标签) 然而,当我调用reloadData时,单元格中的标签并没有被清理和放置新的值,它实际上是在已经存在的标签之上堆叠的。比如你拿了数字200,在上面放了一个50。你们会得到一个奇怪的网格0和5在彼此的上面 关于如何调整这一点有什么想法吗?是否必须将标签的文本重置为“”每个视图都出现了?如果是这样的话,最好的方法是什么,我已经尝试过cellForRowAtIn

在用户从上一个屏幕中选择一个值,导航控制器弹出该值后,我试图更新单元格内的标签(注意,这不是单元格的标签文本。它是单元格内的另一个自定义标签)

然而,当我调用reloadData时,单元格中的标签并没有被清理和放置新的值,它实际上是在已经存在的标签之上堆叠的。比如你拿了数字200,在上面放了一个50。你们会得到一个奇怪的网格0和5在彼此的上面

关于如何调整这一点有什么想法吗?是否必须将标签的文本重置为“”每个视图都出现了?如果是这样的话,最好的方法是什么,我已经尝试过cellForRowAtIndexPath方法,但没有改变

cellforRowAtIndexPath代码

 // Set up the cell...
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    // get the dictionary object
NSDictionary *dictionary = [_groups objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"key"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;

//label for currently selected/saved object
_currentSetting = [[UILabel alloc] initWithFrame:CGRectMake(160, 8, 115, 25)];
[_currentSetting setFont:[UIFont systemFontOfSize:14]];
_currentSetting.backgroundColor = [UIColor clearColor];
_currentSetting.textColor = [UIColor blueColor];
_currentSetting.textAlignment = NSTextAlignmentRight;

_currentSetting.text = [NSString stringWithFormat:@""];
_currentSetting.text = [NSString stringWithFormat:@"%@ mi",[setting.val stringValue]];

 [cell.contentView addSubview:_currentSetting];

 return cell

您正在重新创建标签,并在每次刷新单元格时重新添加标签。只有在第一次创建单元时,才应添加所有单元子视图

因此,在您的代码中,您第一次创建了一个单元格和所有子视图。然后,如果您需要一个新的单元格进行滚动或任何其他原因,您会得到一个可重用的单元格,该单元格已经添加了所有子视图(可重用…)。然后,您将完成添加子视图(再次)的过程,因此,现在该单元包含来自该单元以前所有者(数据)和该单元新所有者(数据)的子视图。这就是为什么在重新加载数据时,它们会叠在一起

seudo代码:

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
   if (cell == nil) {
      //Add all subviews here
   }

   //Modify (only modify!!) all cell subviews here

   return cell;
}

邮政编码。cellForRowAtIndexPath.啊,我知道现在发生了什么。好的,所以基本上,我所有的_currentSetting初始化都需要进入if,然后只在if之外修改它。很好,是的。最简单的方法是将标记添加到单元的子视图中,然后按标记获取它们。一个稍微困难的方法是创建一个定制的tableviewcell类,并使子视图成为类变量。或者你可以停止使用可重复使用的细胞。。。但苹果并不推荐这样做。
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
   if (cell == nil) {
      //Add all subviews here
   }

   //Modify (only modify!!) all cell subviews here

   return cell;
}