1

在用户从前一个屏幕中选择一个值并且导航控制器将它们弹回之后,我正在尝试更新单元格内的标签(注意,这不是单元格的标签文本。它是单元格内的另一个自定义标签)。

但是,当我调用 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
4

2 回答 2

2

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

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

伪代码:

(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;
}
于 2013-01-31T15:05:20.243 回答
1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UILabel *customLabel;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        customLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,320,44)];
        customLabel.tag = 123;
        [cell addSubview:customLabel];
    } else {
        customLabel = (UILabel *)[cell viewWithTag:123];
    }

    customLabel.text = @"Some nice text";

    return cell;
}
于 2013-01-31T15:03:02.673 回答