Skip to content

SwiftUI: ScrollView

Scroll view gives you the flexibility of scrolling through content. Since there isn’t a UITableView(now called List) and UICollectionView, ScrollView could be really useful in filling up the missing gap.

You can even set the direction of the scroll view to be either vertical or horizontal.

A scrollable view.

Apple Documentation

In this tutorial, you’ll learn what it takes to build scroll view in SwiftUI. You’ll learn:

  • How to build scroll view from scratch.
  • How to build a horizontal scroll view.
  • How to build a vertical scroll view.

Prerequisites

To follow along this tutorial, you’ll need some basic knowledge in:

  • A basic familiarity with Swift.
  • At least Xcode 11

Scroll View

The first step to creating a scroll view is exceptionally easy where you will be able to indicate whether you would like it to scroll horizontally or vertically. And by using a bool, you could even hide the indicator.

Horizontal Scroll View

Now, you will create a horizontal scroll view will consists of several rectangle that contain different colors.

First, you will create an array of colors.

Then you will indicate your scroll view requirement which is horizontal in this case and no indicator. You will also be needing some padding to create some space on the leading and trailing.

Then, you will run a ForEach of the array inside the scroll view created above. This will then insert the color into each Rectangle created.

Vertical Scroll View

Now, let it scroll vertically. Using the code above, you will need to make the following changes:

  1. Change .horizontal to .verticalto change scrolling direction
  2. Change HStack to VStack (HStack works too but for more obvious result, VStack is best)

Where to go From Here

If you feel like you are ready to take on more challenges, feel free to check out some other tutorials that we have created:

Published inSwiftUI

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © DaddyCoding 2020.