旧解决方案:
因为你没有显示任何代码。
这是给你的例子。
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
}
关注THIS 教程了解更多信息。希望这会对你有所帮助。
新解决方案:
这是我的朋友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 方法中以这种方式将图像分配给单元格:
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 在评论中建议的那样,这里有一些有用的库可供您使用:
- https://github.com/Alamofire/AlamofireImage
- https://github.com/onevcat/Kingfisher
- https://github.com/rs/SDWebImage
- https://github.com/kean/DFImageManager