iosuitableviewswift3uiactivityindicatorview

Add a ActivityIndicator to the bottom of UITableView while loading


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 ;)


Solution

  • 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.