Search code examples
swifttableviewreloaddata

How i know reloadData has finished


I have a TableView with some cells that has a buttom to Begin an Activityindicator, and it updates that cell, but I'm trying to finish my ActivityIndicator only when the reloadData() has finished, but with the answers that I saw with dispatch_async, isn't working because the Indicator finish first, then it updates The TableView

EDIT

DispatchQueue.main.async(execute: {

              self.tableView.reloadData()

              //From here
              self.initOrEndMed = false                                           
              let myAlert = UIAlertController(title: "Alerta", message: "Tratamento finalizado", preferredStyle: UIAlertControllerStyle.alert)
              let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: {(alert: UIAlertAction!) -> Void in

                                         self.loadingView(loadingText: "", on: false)  

                                        })

              myAlert.addAction(okAction)
              self.present(myAlert, animated: true, completion: nil)
             //To here i want to do after reloadData has finished
                                    })

This is my loadingView()

func loadingView(loadingText: String, on: Bool) {

    self.labelForLoad.text = loadingText
    self.labelForLoad.textAlignment = .center
    self.labelForLoad.numberOfLines = 2
    self.labelForLoad.sizeToFit()
    self.labelForLoad.textColor = UIColor(red:0.24, green:0.69, blue:1.00, alpha:1.0)
    self.labelForLoad.center = CGPoint(x: activityIndicator.center.x, y: activityIndicator.center.y + 40)

    self.overlay.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    self.overlay.addSubview(labelForLoad)

    if on {

        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.5)
        overlay.alpha = overlay.alpha > 0 ? 0 : 0.95
        UIView.commitAnimations()
        self.view.isUserInteractionEnabled = false
        activityIndicator.startAnimating()

    } else {

        self.view.isUserInteractionEnabled = true
        overlay.alpha = 0
        activityIndicator.stopAnimating()
    }

}

Solution

  • There isn't any method which will tell you that UITableView has finished loading all cells. A workaround is to check if indexPath.row is last item in your data set when you get this dataSource callback -

    tableView(UITableView, cellForRowAt: IndexPath)

    and then call loadingView() from within cellForRowAt: method.