Create a Stretchy Header in Swift
And do it in fewer than 5 lines of code
Stretchy headers are a common UI element seen in various apps like Twitter, Facebook, and Spotify. They add a visual flair to the app, and as daunting it may seem to add, they are really a cakewalk once you figure out what’s going on. So today, we’ll add a stretchy header to our own app!
Create a new Xcode project. Name it whatever you want and save it wherever you want on your system. We just want to get to the fun part real quick!
In your freshly created Xcode project, go to Main.storyboard and add a UIImageView to it. Pin it to the leading, trailing, and top edges of the super view so that it expands according to the width of the screen and sticks itself to the top of the screen. Also, add a height constraint of 300, or whatever you like, to the image.
Now, add a UITableView in the ViewController and pin it to all four edges of the view so that it covers the full of the view. It would be overlapping the UIImageView you just inserted, but that’s fine! We’ll fix it in the next steps.
Now, we’ll create IBOutlets to reference these elements in code. We’ll create an IBOutlet for UITableView, UIImageView, and UIImageView’s height constraint.
Now, we’re going to add some setup code so that our view looks the way it is intended to look. I added an image to Assets.xcassets folder of the app, named joker, and set it as the UIImageView’s image.
The Fun Part
The trick to getting this effect is that we will create a transparent cell of the same height as the UIImageView and then start our actual content (same as giving the tableview a contentInset of the height of the image). We’ll update the UIImageView’s height whenever the user scrolls up or down.
We get a callback whenever the table is scrolled, in the scrollViewDidScroll method. So, we’ll override this method and insert our own custom code in it.
What we did above:
- We determined the height, which is our regular height subtracted from the contentOffset. When we scroll upwards, the contentOffset is actually negative, so it gets added to the regular height (subtracting negative quantity will actually add it) so it expands.
- We manipulate the height constraint to whatever we figured out the height was in the first step.
A couple of pointers:
- Make sure the contentMode of UIImageView is scaleAspectFill.
- Make sure the contentAdjustmentBehaviour of UITableView is set to never.
You can add this header effect to really uplift your app from the rest of the apps, and it also looks visually appealing. You can also play with the standard height of the image just to get that pixel-perfect look that works for you. And all of that in just under five lines of code!