单元格文本在滚动时重叠

时间:2012-10-07 19:18:28

标签: ios objective-c iphone uitableview

当我滚动我的tableview时,文本将从下面的单元格中获取所有内容。这可能是因为我每次加载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;
}

1 个答案:

答案 0 :(得分:0)

每次使用单元格时,都会为新标签分配和初始化。滚动期间会重复使用单元格,因此每次都会使用乘法标记。

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

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

相关问题