Как очистить ячейку таблицы для повторного использования - PullRequest
1 голос
/ 12 декабря 2011

Я переписываю некоторый код, чтобы улучшить производительность просмотра таблицы.Я пытаюсь реализовать dequeueReusableCellWithIdentifier, но без особой удачи.

Когда ячейка выходит за пределы экрана и снова включается, ее содержимое дублируется (каждый раз, когда оно выключается и возвращается на экран).Содержимое ячейки также появляется в других ячейках, когда они не должны быть.

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

Сами ячейки состоят из 4 кнопок изображения CUSTOM и четырех меток подряд:

[ ]  [ ]  [ ]  [ ]
abc  abc  abc  abc

В некоторых ячейках все эти изображения / метки могут быть заполнены, в других - только 1 или 2.

Код ниже ..

- (UITableViewCell *)tableView:(UITableView *)thetableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSString *CellIdentifier = [NSString stringWithFormat:@"Cell",indexPath.section];
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    else
    {
        //Tried this to clear old contents but doesn't make a difference
        for (HomeScreenButton* b in cell.subviews)
        {
            NSLog(@"RemovedOldButton");

            b = nil;
        }
        for (UILabel* b in cell.subviews)
        {
            NSLog(@"RemovedOldLabel");

            b = nil;
        }
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    int section = indexPath.section;


    NSMutableArray *sectionItems = [sections objectAtIndex:section]; //Gets the array of objects for this section 
    if (sectionItems.count == 0) return cell;

    LepidEntity * le = [sectionItems objectAtIndex:0];// Gets the object for this section (family/group etc.)


    if (([le.type isEqualToString:@"family"]) || ([le.type isEqualToString:@"group"]))
    {
        NSMutableArray * tmpAnn;
        int annCount = 0;
        //Get annotations for this family/group
        if ([le.type isEqualToString:@"family"])
        {
            Family * family = (Family *)le;
            tmpAnn = [[NSMutableArray alloc]initWithArray:family.annotations];
        }
        else
        {
            Group * group = (Group *)le;
            tmpAnn = [[NSMutableArray alloc]initWithArray:group.annotations];

        }
        annCount = tmpAnn.count;
        //We want to start at the last item in the array. indexPath.row*4. First row would be 0 then 4, then 8 etc.
        for (int i = indexPath.row*4;i < tmpAnn.count;i++)
        {
            Annotation * theAnnotation = [tmpAnn objectAtIndex:i];
            CGRect bRect = CGRectMake(i*80, 5, 80, 80);
            HomeScreenButton *button = [self getResultsViewButton:bRect imagePath:theAnnotation.image cellForRowAtIndexPath:indexPath i:i entity:theAnnotation];
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:button];
            [button release];
            button = nil;
            //Get and configure the label
            CGRect lRect = CGRectMake(i*80, 80, 100, 16);
            UILabel *label = [self getResultsViewLabel:lRect text:theAnnotation.name cellForRowAtIndexPath:indexPath i:i];
            [cell.contentView addSubview:label];
            [label release];
            label = nil;
        }
    }
    else
    {
        Species * s;
    }

    return cell;}

-(HomeScreenButton *) getResultsViewButton:(CGRect)rect imagePath:(NSString *)image 

    cellForRowAtIndexPath:(NSIndexPath *)indexPath i:(int)i entity:(LepidEntity *)entity
    {
        HomeScreenButton *button=[[HomeScreenButton alloc] initWithFrame:rect];

        image = [image stringByReplacingOccurrencesOfString:@"Images/" withString:@"Thumbs/"];

        UIImage *buttonImageNormal=[UIImage imageWithContentsOfFile:GetFullPath(image)];//imageNamed:image];
        [button setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
        [button setContentMode:UIViewContentModeCenter];
        NSString *tagValue = [NSString stringWithFormat:@"%d%d", indexPath.section+1, i];
        button.tag = [tagValue intValue];
        button.entity = entity;
        return button;
    }

Ответы [ 2 ]

1 голос
/ 12 декабря 2011

Вы должны позвонить [b removeFromSuperview] вместо того, чтобы установить его на ноль.

0 голосов
/ 12 декабря 2011

Удалить первое условие еще ..

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