NEW: Nominations are now open for the 2019 Swift Community Awards! >>

How to add horizontal and vertical scrolling using ScrollView

Paul Hudson    @twostraws   

Fully updated for Xcode 11.1

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.

For example, we could create a scroll list of ten text views like this:

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

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)
        }
    }
}

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) {

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

Similar solutions…

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.7/5