Question

I have a prototype UITableViewCell with two UIImageView

I create the cell like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *CellIdentifier = @"PollCell";
        PollListVO * pollist = [self.pollListArray objectAtIndex:indexPath.section];
        PollCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        PollVO *pollVO = [pollist.polls objectAtIndex:indexPath.row];
        cell.pollVO = pollVO;
        return cell;
}

in the cell I have a method:

- (void) setPollVO:(PollVO *)pollVO
{
    NSString *iconName;
    if ([pollVO.author isEqualToString:@"Иванов"]) {
        iconName = @"image_common_from_mayor.png";
    } else if ([pollVO.author isEqualToString:@"Петров"]) {
        iconName = @"image_common_from_government.png";
    } else if ([pollVO.author isEqualToString:@"Сидоров"]) {
        iconName = @"image_common_from_edition.png";
    }
    if (iconName) {
        _mainIconImageView.image = [UIImage imageNamed:iconName];
    }
    _titleLabel.text = pollVO.title;
    _detailLabel.text = pollVO.author;
    _questionLabel.text = [[self class] stringWithQuestionsQuantity:pollVO.questionsQuantity];
    _bounceLabel.text = [[self class] stringWithPointValue:pollVO.points];
    _bounceDetailLabel.text = [SCUtils stringPointsCount:pollVO.points];
    _pollVO = pollVO;
}

and than in layout subviews I change the position and the hidden property for the elements according to the data;

the problem is that after I scrolling the cell - I have the images on the cell from the previous cell - but it shouldn't appears on this particular cell. So it after reusing the cell it takes the icons from the other cell sometimes.

Where is the mistake? How can I solve the issue?

Was it helpful?

Solution

The problem is that when you reuse cell it keeps the image (and all the attributes) that has been set before. In order to correct this behavior you can set the image to nil each time :

if (iconName) {
    _mainIconImageView.image = [UIImage imageNamed:iconName];
}else{
    _mainIconImageView.image = nil;
}

Or in PollCell.m, override prepare for reuse :

- (void) prepareForReuse{
    [super prepareForReuse];
    self.image = nil;
}

OTHER TIPS

if a UITableView gets reused, it will keep its former state. you have to reset all your views and properties every time the cell gets reused to overwrite all the properties.

for your image you could, for example, change your code to:

if (iconName) {
    _mainIconImageView.image = [UIImage imageNamed:iconName];
}else {
    _mainIconImageView.image = nil
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top