Keith
Keith

Reputation: 2009

Display Activity Indicator in tableview cell

I'm loading different images in a basic tableview cell and would like to show the activity indicator in the cell while the image is loading. I'm using a separate cell file like sample code. I know where to place the code just not exactly sure about the syntax. I've found a few ways to put code into a view but not specifically in a cell. Anyone have an idea? Thanks.

func configureCell(favorite: Article) {
    self.favorite = favorite

    downloadImage(NSURL(string: self.favorite.mainImage)!)

func downloadImage(url: NSURL, type: String) {
    getDataFromUrl(url) { (data, response, error) in
        //show activity indicator
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            guard let data = data where error == nil else { return }
                self.mainImage.image = UIImage(data: data)
        }
    }
}

func getDataFromUrl(url: NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError?) -> Void)) {

    NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
        completion(data: data, response: response, error: error)
    }.resume()

}

Upvotes: 3

Views: 6122

Answers (1)

Santosh
Santosh

Reputation: 2914

You could do like below, let me know if that works for you, you can modify the frame as per your requirement.

func downloadImage(url: NSURL, type: String) {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.frame = self.mainImage.bounds

    getDataFromUrl(url) { (data, response, error) in
        //show activity indicator
        self.mainImage.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            guard let data = data where error == nil else { return }
            activityIndicator.stopAnimating()
            activityIndicator.removeFromSuperview()
            self.mainImage.image = UIImage(data: data)
        }
    }
}

Upvotes: 4

Related Questions