【问题标题】:Cell text overlapping on scrolling滚动时重叠的单元格文本
【发布时间】:2012-10-07 19:18:28
【问题描述】:

当我滚动我的表格视图时,文本从下面的单元格中全部混合在一起。这可能是因为每次加载 cellForRow 时我都会重新创建 UILabel,但我不知道如何修复它:

 (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];

    NSDictionary *currentRowDictionary = nil;
    if (tableView == [[self searchDisplayController] searchResultsTableView])
        currentRowDictionary = [[self searchResults] objectAtIndex:row];
    else
        currentRowDictionary = [[self tableData] objectAtIndex:row];

    NSString *voornaam = [currentRowDictionary objectForKey:@"voornaam"];
    NSString *achternaam = [currentRowDictionary objectForKey:@"achternaam"];
    NSString *tussenvoegsel = [currentRowDictionary objectForKey:@"tussenvoegsel"];

    voornaamLbl = [[[UILabel alloc] initWithFrame:CGRectMake(5, 10, 300, 40)] autorelease];
    voornaamLbl.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:19];
    voornaamLbl.text = voornaam;
    voornaamLbl.numberOfLines = 0;
    [voornaamLbl sizeToFit];

    tussenvoegselLbl = [[[UILabel alloc] initWithFrame:CGRectMake(voornaamLbl.frame.size.width + 10, 10, 300, 40)] autorelease];
    tussenvoegselLbl.text = tussenvoegsel;
    tussenvoegselLbl.numberOfLines = 0;
    [tussenvoegselLbl sizeToFit];

    static NSString *CellIdentifier = @"Cell";

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

    [cell.contentView addSubview:voornaamLbl];
    if ([tussenvoegsel length] != 0)
    {
        [cell.contentView addSubview:tussenvoegselLbl];
        achternaamLbl = [[[UILabel alloc] initWithFrame:CGRectMake(voornaamLbl.frame.size.width +
                                                                tussenvoegselLbl.frame.size.width + 15, 10, 300, 40)] autorelease];

    } else {
        achternaamLbl = [[[UILabel alloc] initWithFrame:CGRectMake(voornaamLbl.frame.size.width + 10, 10, 300, 40)] autorelease];
    }

    achternaamLbl.text = achternaam;
    achternaamLbl.numberOfLines = 0;
    [achternaamLbl sizeToFit];

    [cell.contentView addSubview:achternaamLbl];

    return cell;
}

【问题讨论】:

    标签: ios objective-c iphone uitableview


    【解决方案1】:

    每次使用单元格时,您都分配并初始化新标签。单元格在滚动过程中被重复使用,因此您每次都会增加标签。

    最好的方法是创建一个单独的 UITableViewCell 子类,在加载时创建标签,然后在 cellForRowAtIndexPath 中使用新的单元格子类并设置标签文本

    本教程的结尾可以帮助细胞子类http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多