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.
1 |
ScrollView(axes: Axis.Set, showsIndicators: Bool, content: () -> _) |
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.
1 |
var colors = [Color.green, Color.yellow, Color.orange, Color.blue] |
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.
1 2 3 4 |
ScrollView(.horizontal, showsIndicators: false) { } .padding(.horizontal) |
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.
1 2 3 4 5 6 7 |
HStack { ForEach(self.colors, id: \.self) { color in RoundedRectangle(cornerRadius: 4) .fill(color) .frame(width: 250, height: 200) } } |

Vertical Scroll View
Now, let it scroll vertically. Using the code above, you will need to make the following changes:
- Change
.horizontal
to.vertical
to change scrolling direction - Change
HStack
toVStack
(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:
Be First to Comment