11

我已经使用苹果在此处提供的示例在我的应用程序中成功实现了图像的延迟加载。问题是,我希望在滚动时加载图像,但只有在我完成拖动时才将图像加载到单元格中(从屏幕上松开手指。在此之前单元格保持为空)。我已将代码修改如下:

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

    //NSLog(@"cell for row at indexpath, size - %f, current - %d", flowTable.contentSize.height, self.current);

    NSString *CellIdentifier = @"FlowCell";

    MyFlowCell *cell = (MyFlowCell *)[self.flowTable dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FlowCell" owner:nil options:nil];
       // cell = [nib objectAtIndex:0];

        for(id currentObject in nib)

        {

        if([currentObject isKindOfClass:[MyFlowCell class]])

        {
            cell = (MyFlowCell *)currentObject;

            break;
        }
        }
    }

    ImageDetails *rowItem = [self.imageData objectAtIndex:indexPath.row];

    if (!rowItem.mainImage)
    {  
       // if (self.flowTable.dragging == NO && self.flowTable.decelerating == NO)
       // {

            [self startIconDownload:rowItem forIndexPath:indexPath];

        //}

        cell.mainImage.backgroundColor = [UIColor grayColor];

    }
    else
    {

            cell.mainImage.image = rowItem.mainImage;

    }
    }


    return cell;
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
      //  [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //[self loadImagesForOnscreenRows];
}

此外,我发现在我的 ImageDownloader 类中, NSURLConnection 甚至在我从屏幕上松开手指之前都没有收到响应。我一直试图找出为什么会发生这种情况,但到目前为止我还没有成功。如果我遗漏了什么,请告诉我。

4

5 回答 5

9

更新的答案:

标准的 Apple LazyTableImages存在一些缺陷:

  1. 在滚动完成之前,它不会尝试检索图像。我理解他们为什么选择这样做(可能不想检索可能正在滚动的图像),但这会导致图像出现的速度比必要的慢。

  2. 它不会将并发请求的数量限制为某个合理的数量。是的,NSURLConnection会自动冻结请求,直到最大请求数降至某个合理数量,但在最坏的情况下,您实际上可以让请求超时,而不是简单地正确排队。

  3. 一旦它开始下载图像,即使单元格随后滚动离开屏幕,它也不会取消它。

简单的解决方法是退出IconDownloader所有滚动/减速逻辑,只使用或中的UIImageView类别。SDWebImageAFNetworking

如果您要自己解决此问题,则需要做一些工作才能使所有这些都正确。但这里有一个 LazyTableImages 的演绎版,用于NSOperationQueue确保我们 (a) 限制并发请求;(b) 允许我们取消请求。我承认我更喜欢上面的UIImageView类别实现,更好,但我试图保持苹果原始的结构LazyTableImages,同时弥补我上面列举的缺陷。

于 2013-01-18T14:58:12.280 回答
8

您可以按照以下步骤在 tableview 中实现延迟加载:

在您的 Class.h 中,输入:

NSMutableDictionary *Dict_name;
BOOL isDragging_msg, isDecliring_msg;

现在在 Class.m 文件中,将此代码放在视图中确实加载:

Dict_name = [[NSMutableDictionary alloc] init];

在 cellForRowAtIndexPath 中:

if ([dicImages_msg valueForKey:[[msg_array objectAtIndex:indexPath.row] valueForKey:@"image name or image link"]]) { 
    cell.image_profile.image=[dicImages_msg valueForKey:[[msg_array objectAtIndex:indexPath.row] valueForKey:@"image name or image link"]];
}
else
{
    if (!isDragging_msg && !isDecliring_msg)
    {
        [dicImages_msg setObject:[UIImage imageNamed:@"Placeholder.png"] forKey:[[msg_array objectAtIndex:indexPath.row] valueForKey:@"image name or image link"]];
        [self performSelectorInBackground:@selector(downloadImage_3:) withObject:indexPath];
    }
    else
    {
        cell.image_profile.image=[UIImage imageNamed:@"Placeholder.png"];
    }
}

对于下载图像,功能是:

-(void)downloadImage_3:(NSIndexPath *)path{
    NSAutoreleasePool *pl = [[NSAutoreleasePool alloc] init];

    NSString *str=[here Your image link for download];

    UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str]]]; 

    [dicImages_msg setObject:img forKey:[[msg_array objectAtIndex:path.row] valueForKey:@"image name or image link same as cell for row"]];

    [tableview performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];

    [pl release];
}

最后将这些方法放入您的类中:

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    isDragging_msg = FALSE;     
    [tableview reloadData];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    isDecliring_msg = FALSE;
    [tableview reloadData]; 
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    isDragging_msg = TRUE;
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    isDecliring_msg = TRUE; 
}
于 2013-01-18T14:08:53.193 回答
1

假设您的 UITableViewCell 具有图像的 url 属性和 UIImage 属性(加上队列的属性或静态值:

- (void) setThumbnailUrlString:(NSString *)urlString
{
    thumbnailUrlString = urlString;

    NSURL *url = [NSURL URLWithString:urlString];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    if ( queue == nil )
    {
        queue = [[NSOperationQueue alloc] init];
    }
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * resp, NSData     *data, NSError *error) 
    {
        dispatch_async(dispatch_get_main_queue(),^ 
                       {
                            if ( error == nil && data )
                            {
                                UIImage *urlImage = [[UIImage alloc] initWithData:data];
                                thumbnail.image = urlImage;
                            }
                       });
    }];
}

您的实现问题是您的图像加载方法可能发生在主线程中。您需要异步加载图像,然后在主线程中更新图像。

为了正确,该块应该检查响应的 url 是否与请求的 url 匹配,如果单元格的图像在单元格被重新用于不同的图像之前加载得太晚。

于 2013-01-18T14:44:51.557 回答
0

我已经完成了这个包含延迟加载控制器的框架。它易于使用且开箱即用。 https://github.com/cloverstudio/CSUtils 教程可以在这里找到:http: //www.clover-studio.com/blog/using-csutils-ios-framework-for-lazy-loading-images/

于 2014-01-30T13:24:29.863 回答
0

这是一个很晚的答案,但随着 iOS 版本的变化,方法也在不断变化。

为了延迟加载图像,推荐的方法如下:

  1. 下载所有图像的 URL 并将它们存储到您的容器中(数组/对象等)
  2. 触发在后台队列上异步运行的NSURLSessionTask (仅限 iOS 7 之后)。如果您低于 iOS 7,则可以使用NSURLConnection SendAsynchronousRequest API - 它在 iOS 9 中已被弃用,因此您最好尽快摆脱它。
  3. 在后台队列中创建图像
  4. 回到主队列,确保你得到了正确的 UITableViewCell,然后更新图像

这里 -我的教程中描述了整个方法。

于 2015-12-25T19:50:19.493 回答