Today, let’s take a look at how we’d make the following with Swift
Notice how not only does our header stretch as we pull down, it also stops decreasing in size at a certain point. This is reminiscent of the Twitter app when you’re looking at someone’s profile. We want to build a robust implementation here that will work with anything that extends UIScrollView, such as UITableView, UICollectionView, and UIScrollView itself.
Go ahead first and make your header view. In my case, for demo purposes, I’m just gonna use a UIImageView. Now create a UIViewController subclass.
We want first add the header view above the tableview. So first add the UITableView as a subview of your view controller’s view, and pin the top to the top of the safe area guidelines. Now add your customer header view, not as a subview of the UITableView but as a subview of the same view that your UITableView is a subview of, and pin the top of that also to the top of the safe area guidelines. You should have something like this.
Now one last thing, add a height constraint to your header view. If your view expands based on how it’s populated you’ll have to figure out the details of this constraint yourself. But my UIImageView will always have the same height, so I’m just gonna set a height anchor with a 150 constant to my header view. Now you need to get a reference to the tableview (or whatever UIScrollView subclass you’re using), the header view, and the height constraint. Add a property to your view controller to keep the original value of that height constraint.
Next, we’re just gonna set some stuff up. In viewDidLoad(), initialise that saved height constraint, by just setting it to your header view height constraint constant value before it’s changed. This is just so we can reference it later without having to write 150 everywhere. Then we need to offset both the content and scroll bar indicators of our UIScrollView subclass.
The final step to the puzzle is in scrollViewDidScroll. This is a method that gets called on any UIScrollView subclass, and since UITableView extends UIScrollView, we can access it here. In this method, we’re just gonna calculate the y offset and the new height. The height will use the min and max functions. Then we set the height constraint constant value to the new height we calculated.
The height calculation is basically saying, if the y offset is less than 60, return 60. If the y offset is bigger than 400, return 400. Else return the y offset. So our header can’t go smaller than 60 points, and can’t get bigger than 400 points. You can tweak these values if you need to. And that’s it! By not making this the header view of our UITableView, we’ve build a solution that will work with any UIScrollView subclass.