In this tutorial we’re going to build a horizontal scroll view (also known as horizontal list) that is placed along the top of the screen. It’s a simplified version of Instagram stories feature which enables you to horizontally scroll through the images of people you follow. Instead of images, we’re going to use circles to simplify the solution.
The end result is going to look like this:
Create single circle view
First of all, let’s design and define a single circle view which we’ll re-use in the final implementation to compose the entire scroll view. As you can see in the screenshot above, each circle view contains a label placed on top of the circle shape. We’re going to use a @State variable to hold label’s value.
Create a CircleView with a Circle shape and Text view wrapped in a ZStack:
struct CircleView: View {
@State var label: String
var body: some View {
ZStack {
Circle()
.fill(Color.yellow)
.frame(width: 70, height: 70)
Text(label)
}
}
}
The Circle shape is filled with solid color and by applying the frame() modifier we’re fixing it’s size.
Create ScrollView with multiple CircleViews
Now, we’re ready to implement our horizontal scroll view and fill it with several instances of CircleView.
In order to place the scroll view on top of the the screen, we’re going to wrap it in a VStack. Add dividers before and after the scroll view to visually separate the contents of scroll view from the rest of your app:
struct ContentView: View {
var body: some View {
VStack {
Divider()
ScrollView(.horizontal) {
HStack(spacing: 10) {
ForEach(0..<10) { index in
CircleView(label: "\(index)")
}
}.padding()
}.frame(height: 100)
Divider()
Spacer()
}
}
}
In the above example, we’re creating a horizontal ScrollView which contains a horizontal stack view – an HStack. The horizontal stack view contains 10 instances of CircleView created in the ForEach loop, with labels reflecting the index of the item. Entire scroll view with dividers is pushed to the top of the screen by adding a Spacer to expand the empty space at the bottom of the VStack.
We fixed the height of scroll view by applying the frame() modifier.
Build and run your project. The result should look like this:
Related tutorials:
- How to use stacks: HStack, VStack and ZStack in SwiftUI
- How to build a List with custom rows in SwiftUI
- How to customize List in SwiftUI with sections, header and footer
Take a look at Apple’s official documentation of ScrollView in SwiftUI.