【问题标题】:How to put placeholder image and redraw cell when image is downloading from URL?从 URL 下载图像时如何放置占位符图像并重绘单元格?
【发布时间】:2011-02-24 06:29:57
【问题描述】:

我正在尝试将占位符图像放在我的表格视图单元格中。上传图像数据后,是否有触发重绘单元格内容的事件?我正在使用以下内容来创建图像:

[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:photoURLString]]] 

旁注:我正在使用ABTableViewCell 手动绘制单元格的内容,并使用drawInRect 方法。

谢谢。

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    这个调用是同步的,所以当它完成时你的图像就准备好了。

    您可能想要研究的是异步加载图像并在加载时更新图像。

    类似:

    NSURL *url = [NSURL URLWithString:imageURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    

    设置一个属性以包含NSData 并跟踪 NSURLConnection 以便您可以正确释放它。

    self.activeDownload = [NSMutableData data];
    self.imageConnection = conn;
    

    然后提供适当的委托方法来处理连接回调:

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
       [self.activeDownload appendData:data];
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
      // Clear the activeDownload property to allow later attempts
      self.activeDownload = nil;
    
      // Release the connection now that it's finished
      self.imageConnection = nil;
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
      // Set appIcon and clear temporary data/image
      UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
    
      //MAKE Your callbacks and update the image here.
    }
    

    您的回调将要获取该图像,并将其设置为重新加载表格视图将能够正确检索它。 IE。将图像与表格视图单元格使用的其余数据一起设置在数据对象中。

    此外,您可以通过以下方式仅对需要它的单元格进行一次刷新:

    - (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
    

    这是来自 Apple 自己的 LazyImageTables 示例。

    【讨论】:

      【解决方案2】:

      您可以自己执行此操作,但我建议使用 EGOImageLoading,它专为这种确切用途而设计。 在 UITableViewCell 的子类中,不要使用 UIImageView,而是使用 EGOImageView。

      This blog post shows how to use it

      and the code is on github

      (如果您从 github 下载代码,使用网站上的下载按钮获取 zip 或 tar.gz 文件,那么您还需要下载 EGOCache(链接到 github 页面上))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-03
        • 2019-12-24
        • 2015-01-04
        • 1970-01-01
        • 2014-05-12
        • 2017-06-30
        • 2015-07-15
        • 1970-01-01
        相关资源
        最近更新 更多