iphone - uitableviewcell 上的 tableview 中出现重复行

标签 iphone uitableview uilabel

我发现了一些与我的问题相似但不完全相同的帖子。

在我的应用程序中,用户可以在多个 uitableviews 之间导航以深入了解所需的结果。当用户向前、然后向后、然后向前等时,可以注意到行正在被重绘/重写,并且文本变得越来越粗。

我发现在某些帖子中,这可能与我使用 cellforrowatindexpath 方法中的 uilable 创建行的方式有关。

是否需要做一些事情,以便每次用户在 TableView 之间前进和后退时不会重新填充/重绘行?我是否需要在下面的代码中添加一些内容,或者在 viewwillappear 方法中添加一些内容(当前在表的 viewwillappear 中有一个“reloaddata”,但似乎没有帮助)?

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
static NSString *CellIdentifier = @"Cell";

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

    UILabel *label = [[[UILabel alloc] init] autorelease];
    label.font = [UIFont fontWithName:@"Arial-BoldMT" size:20];
    label.frame = CGRectMake(10.0f, 10.0f, 220.0f, 22.0f);
    label.textColor = [UIColor blackColor];
    label.backgroundColor = [UIColor clearColor];
    label.opaque = NO;
    label.text = [mapareaArray objectAtIndex:indexPath.row];
    [cell.contentView addSubview:label];

    CustomCellBackgroundView *bgView = [[CustomCellBackgroundView alloc] initWithFrame:CGRectZero];
    bgView.borderColor = [UIColor clearColor];
    bgView.fillColor = [UIColor whiteColor];
    bgView.position = CustomCellBackgroundViewPositionSingle;
    cell.backgroundView = bgView;
    return cell;
}

最佳答案

您遇到的问题是由这一行引起的:

[cell.contentView addSubview:label];

您正在向表格单元格添加 subview ,无论它是否是新单元格。如果它是旧单元格(从可重用池中出队),那么您将向该单元格添加另一个 subview 。

相反,您应该标记 UILabel,然后使用标记找到它以修改该 UILabel 的内容。在 if( cell == nil ) block 内添加(并设置其所有属性)并标记 UILabel:

if(cell == nil) {
  // alloc and init the cell view...

  UILabel *label = [[[UILabel alloc] init] autorelease];
  label.tag = kMyTag; // define kMyTag in your header file using #define
  // and other label customizations
  [cell.contentView addSubview:label]; // addSubview here and only here
  ...
}

然后通过以下方式找到它:

UILabel *label = (UILabel *)[cell.contentView viewWithTag: kMyTag];
label.text = [mapareaArray objectAtIndex:indexPath.row];

并且无需将其重新添加为 if(cell == nil) block 之外的 subview 。 subview 已经存在(这就是为什么重用单元 View 会更加有效,如果你做得正确的话,那就是;)。

关于iphone - uitableviewcell 上的 tableview 中出现重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1327031/

相关文章:

iphone - 用于插入非音频相关硬件的 API?

ios - 仅为一种单元格类型设置单元格高度并为其他单元格保留动态高度

ios - TableView 不显示单元格中的内容 (Swift)

iphone - UI标签删除线

ios swift ResearchKit 使用 NSPredicate 跳过的条件

iphone - 在哪里可以找到用于 iO 的 Boids 算法的一些开源实现?

iphone - CGPoint 等价于整数?

ios - TableView :indexPath* always returning a nil IndexPath

ios - 将 UIVibrancyEffect 应用于 UITableViewCell 中的 UILabel

ios - 将 UILabel 滑动到 View Controller 上