Horizontal and vertical scrolling using ScrollView in SwiftUI

Updated for Xcode 13.0 beta 2

SwiftUI’s ScrollView allows us to create scrolling containers of views relatively easily, because it automatically sizes itself to fit the content we place inside it and also automatically adds extra insets to avoid the safe area.

Vertical Scrolling

ScrollView {
    VStack(spacing: 20) {
        ForEach(0..<10) {
            Text("Item \($0)")
                .foregroundColor(.white)
                .font(.largeTitle)
                .frame(width: 200, height: 200)
                .background(Color.red)
        }
    }
}
.frame(height: 350)

Horizontal Scrolling

Scroll views are vertical by default, but you can control the axis by passing in .horizontal as the first parameter. So, we could flip our previous example to be horizontal like this:

ScrollView(.horizontal) {
    HStack(spacing: 20) {
        ForEach(0..<10) {
            Text("Item \($0)")
                .foregroundColor(.white)
                .font(.largeTitle)
                .frame(width: 200, height: 200)
                .background(Color.red)
        }
    }
}

Example of Horizontal Scroll

Demo
struct MainTokenCardView: View {
    var body: some View {
        VStack {
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(0..<4) { i in
                        cardView()
                            .padding(2)
                    }
                    Spacer()
                }
                
            }
        }
    }
}

struct cardView: View {
    var body: some View {
        VStack {
            Text("This is a stack")
        }
        .frame(width: 170, height: 100)
        .background(Color.gray.opacity(0.10))
        .cornerRadius(20)
        .shadow(radius: 20)
        .overlay(
            RoundedRectangle(cornerRadius: 20)
                .stroke(Color.gray, lineWidth: 0.5)       
        )
    }
}

You can specify both axes at the same time using [.horizontal, .vertical].

Finally, you can decide whether to show the scroll indicators as the scroll action happens, like this:

ScrollView(.horizontal, showsIndicators: false) {
    HStack(spacing: 20) {
        ForEach(0..<10) {
            Text("Item \($0)")
                .foregroundColor(.white)
                .font(.largeTitle)
                .frame(width: 200, height: 200)
                .background(Color.red)
        }
    }
}

Sources: 1