Search code examples
iostableviewcellgif

GIF imageview not display when tableview scroll back?


I found a very strange thing.

1.I keep a view in my ViewController. enter image description here

  1. add this view in TableView.

`

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
    if(indexPath.row == 0)
    {
        [cell.contentView addSubview:self.imageContainer];
    }else
    {
        if(self.imageContainer.superview == cell.contentView)
        {
            [self.imageContainer removeFromSuperview];
        }
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        return 200;
    }
    else
    {
        return 44;
    }
}

when i scroll to bottom and scroll back to top, the gif not display.why? you can see this picture


Solution

  • Just change one line code as following and your problem is solved:

    from

    if (nil == _imageContainer)

    to

    if (nil == _imageContainer || _imageContainer.superview == nil)

    If there is only one container, in the datasource method, make sure the image is highlighted to get the image loaded. hope it solved your problem.

      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
    if(indexPath.row == 0)
    {
    
        [cell.contentView addSubview:self.imageContainer];
    

    UIImageView * imageView = ( UIImageView *) _imageContainer.subviews[0]; imageView.highlighted = YES;

    }else
    {
        if(self.imageContainer.superview == cell.contentView)
        {
    
             [self.imageContainer removeFromSuperview];
        }
    }
    return cell;
    

    }