How to add Scroll To Top in TableView and CollectionView in iOS using Swift
- August 07, 2019
- John Codeos
In this tutorial, we are going to cover how to implement scroll to the top to your UITableView and UICollectionView very easily.
Scroll to the top is a way to help the user to go at the top of the list fast without the need to scroll manually.
You can do that by making the pressing UINavigationBar‘s Title or with a button that pops up when we start to scroll down.
Add Scroll To Top in Navigation Bar Title for UITableView/UICollectionView
To make the title of UINavigationBar recognize our tap, we need to replace the already existed title, that UINavigationBar has, with a UILabel that recognizes tap gesture to scroll to the top when we pressing it:
After that, we call the function in viewDidLoad() or viewWillAppear() and always after
self.title like this:
NOTE: If the title doesn’t appear, use
self.navigationController?.navigationBar.topItem?.title = "Title"instead of
Add Scroll To The Top in Button for UITableView/UICollectionView
This method is very common when you create a chat. The user scrolls to see their chat history and a button with an arrow appears to scroll back to the conversation.
First, we create the UIView and UIImageView, that contains the arrow, programmatically with the UITapGestureRecognizer and the auto layout constraints:
Next, we’re going to add to our UITableView/UICollectionView the scrollViewDidScroll function.
This function detects the X and Y position of the UIScrollView that UITableView/UICollectionView has. We’re gonna use this to detect when the user starts to scrolls down:
If you want to show the button as soon as the user scrolls down, change the value from 400 to something smaller. The smaller the value, the sooner the Scroll To Top arrow will appear.
And that’s it! Done!
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!