Load More After Coming to Bottom of UITableView

半城伤御伤魂 提交于 2019-12-02 17:48:36

Add a UIActivityIndicatorView (i.e. spinner) to your UITableViewController. Connect the outlet to the code:

@IBOutlet weak var spinner: UIActivityIndicatorView!

Add a property to your UITableViewController to keep track that you're currently loading more data so that you don't try to do it twice:

var loadingData = false

Start the spinner animating and then call refreshResults2():

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if !loadingData && indexPath.row == refreshPage - 1 {
        spinner.startAnimating()
        loadingData = true
        refreshResults2()
    }
}

Have refreshResults2() run on a background thread. This will allow your table to still move freely. The animated spinner will tell the user that more data is coming. Once your query returns, update the table data on the main thread.

func refreshResults2() {
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
        // this runs on the background queue
        // here the query starts to add new 40 rows of data to arrays

        dispatch_async(dispatch_get_main_queue()) {
            // this runs on the main queue
            self.refreshPage += 40
            self.tableView.reloadData()
            self.spinner.stopAnimating()
            self.loadingData = false
        }
    }
}

  • Swift 3 , Xcode 8
  • func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let lastElement = dataSource.count - 1
        if !loadingData && indexPath.row == lastElement {
            spinner.startAnimating()
            loadingData = true
            loadMoreData()
        }
    }
    

    as per @vacawama async call in swift 3:-

    func loadMoreData() {
        DispatchQueue.global(qos: .background).async {
            // this runs on the background queue
            // here the query starts to add new 10 rows of data to arrays
            DispatchQueue.main.async {
                 // this runs on the main queue
                    self.spinner.stopAnimating()
                    self.loadingData = false
    
            }
        }
    }
    
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!