Imran Shams Imran Shams - 8 months ago 39
iOS Question

Swift: load images Async in UITableViewCell

I have a

that I created with code (without

class MSContentVerticalList: MSContent,UITableViewDelegate,UITableViewDataSource {
var tblView:UITableView!
var dataSource:[MSC_VCItem]=[]

init(Frame: CGRect,DataSource:[MSC_VCItem]) {
super.init(frame: Frame)
self.dataSource = DataSource
tblView = UITableView(frame: Frame, style: .Plain)
tblView.delegate = self
tblView.dataSource = self

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)

let record = dataSource[indexPath.row]
cell.textLabel!.text = record.Title
cell.imageView!.downloadFrom(link: record.Icon, contentMode: UIViewContentMode.ScaleAspectFit)
cell.imageView!.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
cell.detailTextLabel!.text = record.SubTitle
return cell

and in other class I have an extension method for download images Async:

extension UIImageView
func downloadFrom(link link:String?, contentMode mode: UIViewContentMode)
contentMode = mode
if link == nil
self.image = UIImage(named: "default")
if let url = NSURL(string: link!)
print("\nstart download: \(url.lastPathComponent!)")
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, _, error) -> Void in
guard let data = data where error == nil else {
print("\nerror on download \(error)")
dispatch_async(dispatch_get_main_queue()) { () -> Void in
print("\ndownload completed \(url.lastPathComponent!)")
self.image = UIImage(data: data)
self.image = UIImage(named: "default")

I used this function in other places and worked correctly, Based on my logs I understand that images downloaded without problem (when the cell is rendered) and after download of image, The cell UI not updated.

Also I tried to use caching library like Haneke but problem is exist and not change.

Please help me to understand mistakes



After setting the image you should call self.layoutSubviews()

edit: corrected from setNeedsLayout to layoutSubviews