Mastering Swift and SwiftUI

Insights, Tips, and Tutorials for iOS Developers

SwiftUI Modifiers Deep Dive: scrollBounceBehavior

Published on Feb 12, 2025

Get a quick glimpse of how Tiny Currency simplifies currency conversion with up to date rates, multi-currency support, and easy-to-use widgets. Perfect for on-the-go use, our app ensures you're always prepared, no matter where your travels take you.

📱 iOS 16.4+

On this deep dive, we are exploring the scrollBounceBehavior SwiftUI modifier, which was added in iOS 16.4.

Apple's Documentation

Use this modifier to indicate whether scrollable views bounce when people scroll to the end of the view’s content, taking into account the relative sizes of the view and its content. For example, the following ScrollView only enables bounce behavior if its content is large enough to require scrolling:

ScrollView {
    Text("Small")
    Text("Content")
}
.scrollBounceBehavior(.basedOnSize)

The modifier passes the scroll bounce mode through the Environment, which means that the mode affects any scrollable views in the modified view hierarchy. Provide an axis to the modifier to constrain the kinds of scrollable views that the mode affects. For example, all the scroll views in the following example can access the mode value, but only the two nested scroll views are affected, because only they use horizontal scrolling:

ScrollView { // Defaults to vertical scrolling.
    ScrollView(.horizontal) {
        ShelfContent()
    }
    ScrollView(.horizontal) {
        ShelfContent()
    }
}
.scrollBounceBehavior(.basedOnSize, axes: .horizontal)

You can use this modifier to configure any kind of scrollable view, including ScrollView, List, Table, and TextEditor:

Usage

The scrollBounceBehavior modifier is pretty straight forward, and handy when you don't want the ScrollView to bounce if the content is less than the size of the view.

There is not much more to be said about it other than it is one of those handy modifiers that feels a bit hidden. I happened to find this one by accident, and I wanted to share it with my readers.

struct ContentView: View {
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                ForEach(0..<50) { index in
                    Text("Item \(index)")
                        .frame(maxWidth: .infinity)
                        .padding()
                        .background(Color.gray.opacity(0.2))
                }
            }
        }
        .scrollBounceBehavior(.automatic)
    }
}

Just keep in mind that the automatic behavior seems to use always and never uses basedOnSize unless specifically set.