1

When I scroll my tableview, the text gets all mashed up from the cells below. It's probably cause I recreate the UILabels every time cellForRow gets loaded, but I wouldn't know how to fix it:

 (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;
}
4

1 回答 1

0

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

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

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

于 2012-10-07T19:36:14.417 回答