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 method, 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()
}
}
}
Code language: Swift (swift)
…and that’s all! Easy, huh???
You can find the final project here
If you have any questions, please feel free to leave a comment below