Add a ActivityIndicator to the bottom of UITableView while loading

Ivan Cantarino picture Ivan Cantarino · Feb 25, 2017 · Viewed 20.4k times · Source

I want to add a ActivityIndicator to the bottom of my UITableView when the last cell is displayed, while I'm fetching more data, then when the data got fetched hide it.

So I scroll to the bottom -> last row displayed -> spinner starts spinning while data is fetched -> Data fetched, hide the spinner -> new data added to the tableview.

Any tips on how can I achieve this?

Thanks ;)

Answer

AyAz picture AyAz · Feb 25, 2017

Add This Function

 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let lastSectionIndex = tableView.numberOfSections - 1
    let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
    if indexPath.section ==  lastSectionIndex && indexPath.row == lastRowIndex {
       // print("this is the last cell")
        let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        spinner.startAnimating()
        spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))

        self.tableview.tableFooterView = spinner
        self.tableview.tableFooterView?.isHidden = false
    }
}

and tableFooterView should hide when data load.