SwiftUI- Stretchable Header View

Oleg Tsibulevskiy
Just Eat Takeaway-tech
3 min readNov 17, 2020

--

In this tutorial, we will learn how to create one of the most popular effects Stretchable Header View using SwiftUI.

Photo by NeONBRAND on Unsplash

SwiftUI is based on Views, so before starting the work will be right to plan scene structure.

Planning

We are going to build a template for a Restaurant Menu screen with a stretchable header. The screen will contain 2 views, a Stretchable Header View and List View. All content will be scrollable, so we must wrap all views with the Scroll View.
Looks easy, so let’s start!

Stretchable Header View

Our header view contains only one view, Image:

First, we need to observe the scrolling direction and header view position to set offset and height. For this, we wrap the content to the GeometryReader which has a height of 25% from the screen height. Inside of GeometryReader we added Image with multiple configurations:

  1. Resizable - Makes it possible to change the image size.
  2. Offset - Sets the header y position on scrolling.
  3. Frame - Sets the header height on scrolling.
  4. AspectRation - Gives us a beautiful zoom-in effect when the view is stretched down.

Menu Items List

From iOS 14 SwiftUI gives us a new instrument to build lists LazyVStack, and we will use it in this tutorial. SwiftUI in comparison with UIKit makes our life easy when we need to add a list of items, we will see how to add LazyVStack by example soon. All that we need to show a list is to create an item view and data model. Let’s start with the data:

Because this is only a template, we will use static data. Let’s create a data repository where we will build the menu items:

Our menu item view will contain an image, title, and description:

The result will be:

Main View

All our views and data are ready, so we can start to build our main view. I will be calling it “Menu”. First, we need to add ScrollView with vertical scrolling direction and inside we need to add our StretchableHeader. To show a list of items we will use LazyVStack introduced by Apple at WWDC 2020. All we have left now is to create MenuItemCards in our LazyVStack by using ForEach loop.

Result

Conclusion

SwiftUI allows us to create beautiful UI without writing a lot of code. I hope you enjoyed this tutorial. Source code. Good luck!

Make sure to check out our careers page to discover tech jobs at Takeaway.com!

--

--