загружая асинхронные изображения в табличное представление, они исчезают при каждой прокрутке - PullRequest
1 голос
/ 02 мая 2011

Я анализирую XML-файл, содержащий URL-адреса для изображений большого пальца.Я хочу показать эти большие пальцы в удобном для просмотра виде.

Используя класс AsyncImageView (находится на этом сайте ), мой код работает.

Единственная проблема заключается в следующем: каждый разчто пользователь прокручивает uitableview, изображения на мгновение исчезают ... затем снова появляются (я думаю, что я загружаю изображение каждый раз, но я не уверен)!

Это ужасный эффект, я хочу, чтобы, если изображение загружено, оно оставалось видимым.

это мой код (примечание: в array_thumb есть ранее проанализированные URL):

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

static NSString *CellIdentifier;
static NSString *NibNamed;

UIDeviceOrientation deviceOrientation = [UIApplication sharedApplication].statusBarOrientation;

if (deviceOrientation != UIDeviceOrientationLandscapeLeft &&
    deviceOrientation != UIDeviceOrientationLandscapeRight)
{
    CellIdentifier= @"Cell1";
    NibNamed = @"cell_gallery";
}
else
{
    CellIdentifier= @"Cell2";
    NibNamed = @"cell_gallery_landscape";
}

[[NSBundle mainBundle] loadNibNamed:NibNamed owner:self options:NULL];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:NibNamed owner:self options:nil];
    cell = [nib objectAtIndex:0];
}
else {
    AsyncImageView* oldImage = (AsyncImageView*)[cell.contentView viewWithTag:1];
    [oldImage removeFromSuperview];
}

CGRect frame;
frame.size.width=72; frame.size.height=72;
frame.origin.x=10; frame.origin.y=10;
AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];

NSString *title = [NSString stringWithFormat:@"%@", [array_title objectAtIndex:indexPath.row]];
UILabel *testoLabel = (UILabel*)[cell viewWithTag:2];
testoLabel.text = title; 


asyncImage.tag = 1;

NSLog(@"%@", asyncImage);

NSURL *url = [NSURL URLWithString:[array_thumb objectAtIndex:indexPath.row]];   
asyncImage.layer.cornerRadius = 10.0;
asyncImage.layer.masksToBounds = YES;
[asyncImage loadImageFromURL:url];

[cell.contentView addSubview:asyncImage];


UIColor *miocolore1 = [[UIColor alloc] initWithRed:247.0 / 255 green:247.0 / 255 blue:247.0 / 255 alpha:1.0];
UIColor *miocolore2 = [[UIColor alloc] initWithRed:233.0 / 255 green:233.0 / 255 blue:233.0 / 255 alpha:1.0];

if (indexPath.row % 2 == 0) {
    cell.contentView.backgroundColor =  miocolore1;
}
else {
    cell.contentView.backgroundColor =  miocolore2;

}


return cell;


}

Ответы [ 2 ]

1 голос
/ 02 мая 2011

Ничто в вашем коде или в AsyncImageView не предполагает, что изображения кэшируются, поэтому кажется, что одно и то же изображение загружается повторно.

AsyncImageView использует следующее для загрузки изображения:

[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];

Возможно, вы захотите убедиться, что кеширование действительно происходит здесь, изменив политику кеширования.

Я бы извлек ASIHTTPRequest , в котором реализована отличная реализация кэша.

0 голосов
/ 02 мая 2011

Поскольку ячейка используется повторно, вы должны предоставить данные самостоятельно.Либо вы можете сохранить загруженный образ как NSData или UIImage и указать URL для загрузки, либо использовать уже загруженные данные.Таким образом, изображение не будет загружаться при каждой прокрутке.

...