Add Pull To Refresh to your iOS app using Swift

Add Pull To Refresh to your iOS app using Swift

Today, I’ll show you how to add Pull To Refresh into your UITableView/UICollectionView very easy.

Adding Pull To Refresh in TableView/CollectionView

We already have an UITableView/UICollectionView filled with data, and we want to add the Pull To Refresh feature.

The only thing we have to do is to create an UIRefreshControl and add it into our UITableView/UICollectionView and trigger a function, to refresh the data, every time we swipe down.

var refControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
// Setting up UIRefreshControl
refControl.tintColor = UIColor.white
refControl.addTarget(self, action: #selector(handleRefresh(refreshControl:)), for: UIControl.Event.valueChanged)
tableView.addSubview(refControl)
// Do other things...
}
@objc func handleRefresh(refreshControl: UIRefreshControl) {
DispatchQueue.global().async {
// Fake background loading task
sleep(2)
// Refresh the data here
DispatchQueue.main.async {
self.tableView.reloadData()
refreshControl.endRefreshing()
}
}
}
view raw pulltorefresh.swift hosted with ❤ by GitHub

…and that’s all! Easy, huh?πŸ•ΊπŸŽ‰

You can find the final project here

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

Leave a Reply

avatar
  Subscribe  
Notify of

Stay Connected

Newsletter

Subcribe for weekly emails! Get my posts of the week right in your inbox!