问题描述
我想使用 swift 为我的表视图使用延迟加载概念.在我的表格视图中,我显示了多个包含产品图片和产品名称的单元格.请帮我找到解决方案.
I want to use lazy loading concept for my table view using swift. In my table view i am showing multiple cells which contain product images and product name .Please help me to get the solution.
推荐答案
旧解决方案:
因为您没有显示任何代码.
Since you doesn't show any code.
这是给你的例子.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// try to reuse cell
let cell:CustomCell = tableView.dequeueReusableCellWithIdentifier("DealCell") as CustomCell
// get the deal image
let currentImage = deals[indexPath.row].imageID
let unwrappedImage = currentImage
var image = self.imageCache[unwrappedImage]
let imageUrl = NSURL(string: "http://staging.api.cheapeat.com.au/deals/(unwrappedImage)/photo")
// reset reused cell image to placeholder
cell.dealImage.image = UIImage(named: "placeholder")
// async image
if image == nil {
let request: NSURLRequest = NSURLRequest(URL: imageUrl!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
image = UIImage(data: data)
self.imageCache[unwrappedImage] = image
dispatch_async(dispatch_get_main_queue(), {
cell.dealImage.image = image
})
}
else {
}
})
}
else{
cell.dealImage.image = image
}
return cell
}
关注本教程了解更多信息.希望这对你有帮助.
Follow THIS tutorial for more Info. Hope this will help you.
新解决方案:
这是它的扩展,它由我的朋友 Leo Dabus 创建,使用起来非常简单:
Here is extension for it which is created by my friend Leo Dabus which is really simple to use:
extension UIImageView {
func downloadImageFrom(link link:String, contentMode: UIViewContentMode) {
NSURLSession.sharedSession().dataTaskWithURL( NSURL(string:link)!, completionHandler: {
(data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
self.contentMode = contentMode
if let data = data { self.image = UIImage(data: data) }
}
}).resume()
}
}
现在在您的 cellForRowAtIndexPath
方法中,以这种方式将图像分配给单元格:
Now in your cellForRowAtIndexPath
method assign image to cell this way:
cell.cellImageView.image = UIImage(named: "placeholder") //set placeholder image first.
cell.cellImageView.downloadImageFrom(link: imageLinkArray[indexPath.row], contentMode: UIViewContentMode.ScaleAspectFit) //set your image from link array.
正如 Rob 在评论中建议的那样,这里有一些您可以使用的有用库:
And as Rob suggested into comment here is some useful libraries which you can use:
- https://github.com/Alamofire/AlamofireImage
- https://github.com/onevcat/Kingfisher
- https://github.com/rs/SDWebImage
- https://github.com/kean/DFImageManager
这篇关于如何使用swift在表格视图中实现图像的延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!