xcode 从 URL 加载图像到表格视图单元格中的图像视图的更快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28905647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Faster way to load image from an URL to image view in table view cell
提问by Utku Dalmaz
I am using this to load URL to image view
我正在使用它来加载 URL 到图像视图
let url = NSURL(string: URL)
let data = NSData(contentsOfURL: url!)
self.releasephoto.image = UIImage(data: data!)
But when there is 10 items in table view cell with different images, scrolling gets slower and hangs
但是当表格视图单元格中有 10 个具有不同图像的项目时,滚动变慢并挂起
I load images with the size of 40 X 40
我加载大小为 40 X 40 的图像
I wonder if there is a better way to load URL images ?
我想知道是否有更好的方法来加载 URL 图片?
回答by Sam
I would suggest using SDWebImage.
我建议使用SDWebImage。
After installing it you'll need to make a bridging header for Swift and include this line:
安装后,您需要为 Swift 制作一个桥接头并包含以下行:
#import "UIImageView+WebCache.h"
Then all you need to do in your cellForRowAtIndexPath function is this:
那么你需要在 cellForRowAtIndexPath 函数中做的就是:
let url = NSURL(string: URL)
self.releasephoto.sd_setImageWithURL(url)
The nice thing about this library is that it automatically caches the image so it's only downloaded once.
这个库的好处是它会自动缓存图像,所以它只下载一次。
回答by matt
You have to load the views asynchronously. Supply a dummy or blank image initially. Then load into your model, asynchronously in the background, any images for cells that are currently showing. As each image arrives, stash it in the model and reload the table view. Thus each image will appear when it happens to arrive, but your scrolling won't be slowed down because there always isan image - the blank or dummy if you have not fetched the image for this row, or the real image if you have fetched it.
您必须异步加载视图。最初提供一个虚拟或空白图像。然后将当前显示的单元格的任何图像在后台异步加载到您的模型中。当每个图像到达时,将其存储在模型中并重新加载表视图。因此,当每个图像碰巧到达时都会出现,但是您的滚动不会减慢,因为总是有一个图像 - 如果您尚未获取该行的图像,则为空白或虚拟图像,或者如果已获取则为真实图像它。
Here's example code from my book:
这是我书中的示例代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath:indexPath) as UITableViewCell
let m = self.model[indexPath.row]
cell.textLabel!.text = m.text
// have we got a picture?
if let im = m.im {
cell.imageView!.image = im
} else {
if m.task == nil { // no task? start one!
cell.imageView!.image = nil
m.task = self.downloader.download(m.picurl) { // *
[weak self] url in // *
m.task == nil // *
if url == nil {
return
}
let data = NSData(contentsOfURL: url)!
let im = UIImage(data:data)
m.im = im
dispatch_async(dispatch_get_main_queue()) {
self!.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}
}
}
}
return cell
}
(The full working example is here. And the code for MyDownloader, the class of self.downloader
, is here.)
(完整的工作示例在此处。MyDownloader 的代码,即 的类self.downloader
,在此处。)
For extra super efficiency, cancel the download if the user scrolls a row out of view before the image arrives. That way you set a cap on how many downloads can be happening at once.
为了获得额外的超级效率,如果用户在图像到达之前将一行滚动到视野之外,则取消下载。这样你就可以设置一次下载的上限。
回答by Kalpesh
I have already answered to the similar question here
我已经在这里回答了类似的问题
Use the following class:
使用以下类:
class ImageLoadingWithCache {
var imageCache = [String:UIImage]()
func getImage(url: String, imageView: UIImageView, defaultImage: String) {
if let img = imageCache[url] {
imageView.image = img
} else {
let request: NSURLRequest = NSURLRequest(URL: NSURL(string: url)!)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
let image = UIImage(data: data)
self.imageCache[url] = image
dispatch_async(dispatch_get_main_queue(), {
imageView.image = image
})
}
else {
imageView.image = UIImage(named: defaultImage)
}
})
}
}
}
Usage:
用法:
var cache = ImageLoadingWithCache()
cache.getImage(YOUR_URL, imageView: YOUR_IMAGEVIEW, defaultImage: "DEFAULT_IMAGE_NAME")
回答by Dino Tw
Apple has a sample code LazyTableImages, although it's in Objective-C. Just like what @Matt mentioned, it has to be done asynchronously.
Apple 有一个示例代码LazyTableImages,尽管它是在 Objective-C 中的。就像@Matt 提到的那样,它必须异步完成。
回答by Will
NSURL *url = [NSURL URLWithString:@"http:url..."];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
UIImage *placeholderImage = [UIImage imageNamed:@"your_placeholder"];
__weak UITableViewCell *weakCell = cell;
[cell.imageView setImageWithURLRequest:request
placeholderImage:placeholderImage
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
weakCell.imageView.image = image;
[weakCell setNeedsLayout];
} failure:nil];
It works fine with AFNetworking 2.
它适用于 AFNetworking 2。