Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show "pull-to-refresh" element at the bottom of the UITableView in Swift

I need to show UIRefreshControl at the bottom of the UITableView like in the following Objective-C libraries:

  • https://github.com/emenegro/bottom-pull-to-refresh
  • https://github.com/vlasov/CCBottomRefreshControl

but I'm using Swift and noticed some problems when using "Bridging-Header.h" file with these libraries.

What is the alternative and the easiest way to achieve such behavior?

Thanks in advance.

like image 243
FrozenHeart Avatar asked Nov 28 '14 14:11

FrozenHeart


People also ask

How do you add a pull to refresh to a table view or collection view?

You can add a refresh control to a table or collection view by assigning an instance of the UIRefreshControl class to this property. If your application targets versions prior to iOS 10, you simply add the refresh control as a subview to the table view.

What is UITableView in Swift?

A view that presents data using rows in a single column.


1 Answers

I got into the same problem in my project, and found this answer. You can add a UIActivityIndicatorView instance on the bottom of the table, initially hidden, and when it enters the if condition above, unhide it and start its animation.

You may need to change the table's bottom offset, add "1 cell" height to it while it's loading and place it back when it finishes inside the if condition as well.

In Swift 3:

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    // Use this 'canLoadFromBottom' variable only if you want to load from bottom iff content > table size
    let contentSize = scrollView.contentSize.height
    let tableSize = scrollView.frame.size.height - scrollView.contentInset.top - scrollView.contentInset.bottom
    let canLoadFromBottom = contentSize > tableSize

    // Offset
    let currentOffset = scrollView.contentOffset.y
    let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
    let difference = maximumOffset - currentOffset

    // Difference threshold as you like. -120.0 means pulling the cell up 120 points
    if canLoadFromBottom, difference <= -120.0 {

        // Save the current bottom inset
        let previousScrollViewBottomInset = scrollView.contentInset.bottom
        // Add 50 points to bottom inset, avoiding it from laying over the refresh control.
        scrollView.contentInset.bottom = previousScrollViewBottomInset + 50

        // loadMoreData function call
        loadMoreDataFunction(){ result in
            // Reset the bottom inset to its original value
            scrollView.contentInset.bottom = previousScrollViewBottomInset
        }
    }
}
like image 158
Carlos Kochhann Avatar answered Sep 21 '22 17:09

Carlos Kochhann