Lazy loading of images in table view using Swift


To load an image in table view cell we’ll go through a series of steps.

Create a table view, table view cell and add an Image view to it.

Assign a custom class to the cell we created.

In the cell for row at method write the following lines of code.

let cell = tblView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
return cell

To download the image we’ll create a function and embed that into an extension.

func setImageFromUrl(ImageURL :String) {
   URLSession.shared.dataTask( with: NSURL(string:ImageURL)! as URL, completionHandler: {
      (data, response, error) -> Void in
      DispatchQueue.main.async {
         if let data = data {
            self.image = UIImage(data: data) 
         }
      }
   }).resume()
}

Now embed the same function into an extension of UIImageView to use with any image.

In Cell for row at method the following function, where img is the outlet in custom Class.

cell.img.setImageFromUrl(ImageURL: url)

In this example I’ve used an image from open source "https://homepages.cae.wisc.edu/~ece533/images/boat.png”

When we run the same code on an iPhone 7+ simulator, below is the result −

Updated on: 30-Jul-2019

955 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements