图像闪烁每次重新加载表(iOS,objective-C)

时间:2015-12-11 20:02:54

标签: ios objective-c uitableview caching

我遇到的问题是,每次调用表reloadData方法时,我的tableview单元格中的图像都会闪烁。闪烁正在发生,因为每次重新加载表时都会下载图像。如何制作,以便每次都不会下载此图像,但只能下载一次?

这是SelectStationViewController.m中的cellForRowAtIndexPath代码。该类处理tableView。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    StationRest * StationRest = [[CurrentUser sharedInstance].userStations objectAtIndex:indexPath.row];
    StationListCell *cell= [[StationListCell alloc]initWithFrame:CGRectMake(0, 0, 375,88)];
    cell.cellDelegate = self;

    //This method below downloads the image into the cell.
    [cell configureCellWithStationRest:StationRest forCellType:StationListCellTypeSelect];

    return cell;
}

这是StationListCell.m中的代码,它是与单元格连接的类。这是使用AFNetworking下载图像的位置。我可以使用[[NSData alloc] initWithContentsOfURL方法而不是AFNetworking来使用GCD,但我仍然可以获得相同的结果。

-(void)configureCellWithStationRest:(StationRest *)stationRest forCellType:(StationListCellType) cellType{

    NSURL *url = [NSURL URLWithString:stationRest.thumbURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];

    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.thumbButton setImage:responseObject forState:UIControlStateNormal];
        [self.thumbButton setContentMode:UIViewContentModeScaleAspectFill];
        } 
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            DLog(@"Image error: %@", error);
        }];

    [requestOperation start];

}

1 个答案:

答案 0 :(得分:2)

您可以使用UIImageView + AFNetworking.h类别。它提供了从url下载图像并缓存它的方法。请查看其文档以获取更多信息。

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[yourImageView setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
    yourImageView.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
    NSLog(@"Failed to load image");
}];