Apart from the List, there is another component for creating a scrollable view of items: the ScrollView. This component allows scrolling vertically (by default) and horizontally.
To learn how to use this component, we will create a carousel. We often see complex interfaces built using carousel components, as seen on Netflix, Amazon, and others. Let’s get started.
First, I’ll show you an example of a carousel built using only text and a rectangle. This is a minimal example meant to help you understand the fundamentals.
As usual, let’s start from the end.

It’s possible to scroll any row horizontally and vertically.
The code:
struct ContentView: View {
var colorsRow: [Color] = [.purple,.yellow]
var body: some View {
ScrollView {
VStack(spacing: 5) {
ForEach(0..<10) { j in
ScrollView(.horizontal) {
HStack(spacing: 5) {
ForEach(0..<10) { i in
VStack {
Text("Item \(i)")
.foregroundColor(colorsRow[j % 2])
.font(.largeTitle)
.frame(width: 200, height: 200)
.background(.black)
}.clipShape(RoundedRectangle(cornerRadius: 20))
}
}
}
}
}.background(.black)
.opacity(0.9)
}.edgesIgnoringSafeArea(.all)
}
}
We use two ScrollViews for this implementation: the first for vertical scrolling (the default behavior) and the second for horizontal scrolling. Note the .horizontal parameter.
In the VStack, we specify the spacing, which determines the space between rows. In the HStack, the spacing defines the space between columns.
The first ForEach loop iterates over the rows, while the second iterates over the columns. The text color is determined using the row index modulo operation.
Finally, we added a bit of opacity for a better look and feel.
Leave a Reply