我想使用swift在表格视图中使用延迟加载概念。在我的表格视图中,我正在显示包含产品图像和产品名称的多个单元格。请帮助我获得解决方案。
旧解决方案:
由于您没有显示任何代码。
这是给你的例子。
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 }
请遵循本教程以获取更多信息。希望这会帮助你。
新解决方案:
这是我的朋友Leo Dabus创建的扩展,使用起来 非常简单:
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方法中,以这种方式将图像分配给单元格:
cellForRowAtIndexPath
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在评论中建议的那样,您可以使用一些有用的库: