Почему UITableViewCell меняет свое значение в одной ячейке? - PullRequest
0 голосов
/ 21 июля 2011

В моем приложении я настроил UITableViewCell и использую его свойство contentView. Но сейчас проблема в том, что данные в ячейках иногда собираются в разных ячейках. Например: данные в ячейке 3 поступают в ячейку 8 или 9 при прокрутке вниз или вверх. Вот код, который я использую в cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";
    CGFloat fontSize = [UIFont systemFontSize];
    CGFloat smallFontSize = [UIFont smallSystemFontSize];
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]autorelease];
        mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(5,0,150,42)] autorelease];
        mainLabel.font = [UIFont systemFontOfSize:smallFontSize];
        mainLabel.numberOfLines = 3;
        mainLabel.lineBreakMode = UILineBreakModeWordWrap;
        mainLabel.backgroundColor = [UIColor clearColor];
        mainLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
        [cell.contentView addSubview:mainLabel];

        secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(160,0,160,42)] autorelease];
        secondLabel.font = [UIFont systemFontOfSize:smallFontSize];
        secondLabel.numberOfLines = 3;
        secondLabel.lineBreakMode = UILineBreakModeWordWrap;
        secondLabel.backgroundColor = [UIColor clearColor];
        secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
        [cell.contentView addSubview:secondLabel];


    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:smallFontSize];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:smallFontSize];
    NSArray * titles = [[NSArray alloc] initWithObjects:@"Project ID", @"Status", @"Approval Date", @"Closing Date", @"Country",@"Region Name", @"Env", @"Team Full Name",@"Borrower", @"Impagency", @"Lending Cost", @"IBRDPlus", nil];

    switch (indexPath.section) {
        case 0:

            mainLabel.text = [titles objectAtIndex:indexPath.row];
            mainLabel.adjustsFontSizeToFitWidth = YES;
            mainLabel.numberOfLines = 4;
            mainLabel.lineBreakMode = UILineBreakModeWordWrap;

            secondLabel.text = [self.basic objectAtIndex:indexPath.row];
            secondLabel.adjustsFontSizeToFitWidth = YES;
            secondLabel.numberOfLines = 4;
            secondLabel.lineBreakMode = UILineBreakModeWordWrap;
            break;
        case 1:

            mainLabel.text = [[self.allSectors objectAtIndex:indexPath.row] valueForKey:@"SECTORNAME"];
            mainLabel.adjustsFontSizeToFitWidth = YES;
            mainLabel.numberOfLines = 4;
            mainLabel.lineBreakMode = UILineBreakModeWordWrap;

            secondLabel.text = [[self.allSectors objectAtIndex:indexPath.row] valueForKey:@"SECTORPCT"];
            secondLabel.adjustsFontSizeToFitWidth = YES;
            secondLabel.numberOfLines = 4;
            secondLabel.lineBreakMode = UILineBreakModeWordWrap;

            break;
        case 2:

            mainLabel.text = [[self.themes objectAtIndex:indexPath.row] valueForKey:@"THEME_NAME"];
            mainLabel.adjustsFontSizeToFitWidth = YES;
            mainLabel.numberOfLines = 4;
            mainLabel.lineBreakMode = UILineBreakModeWordWrap;

            secondLabel.text = [[self.themes objectAtIndex:indexPath.row] valueForKey:@"THEMEPCT"];
            secondLabel.adjustsFontSizeToFitWidth = YES;
            secondLabel.numberOfLines = 4;
            secondLabel.lineBreakMode = UILineBreakModeWordWrap;

            break;

        default:
            break;
    }

    return cell;
}

1 Ответ

1 голос
/ 21 июля 2011

Это происходит из-за этой строки (которую вы должны иметь в любом случае):

UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];

В основном, потому что ячейки используются повторно, содержимое остается в ячейке, поэтому вам нужно очистить эту ячейку после того, какdequeu и затем установите новый contentView.

Что здесь происходит, в частности, это то, что, хотя вы сбрасываете текст secondLabel, когда вы устанавливаете здесь свою переменную:

secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(160,0,160,42)] autorelease];

Последняя созданная ячейка - это то, на что указывает secondLabel, так что вы действительно всегда меняете одну и ту же метку, поэтому я бы предложил что-то вроде этого:

UILabel *lblCell;
for (id label in [cell.contentView subviews]) {
            if ([label isKindOfClass:[UILabel class]]) {
                lblCell = label;
            }
        }

lblCell.text = [[self.themes objectAtIndex:indexPath.row] valueForKey:@"THEMEPCT"];

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...