Search code examples
iosswiftswiftuiuiscrollview

SwiftUI - How to make ScrollView not bounce when content is smaller than bounds


I'm trying to make my ScrollView:

  • Not bounce when the content is smaller than the screen
  • Bounce when the content overflows the screen

Here's my code:

struct ContentView: View {
    init() {
        UIScrollView.appearance().alwaysBounceVertical = false
    }
    var body: some View {
        ScrollView {
            Rectangle()
                .fill(Color.blue)
                .frame(height: 300) /// is smaller than the screen
                .padding()
        }
    }
}

I tried setting UIScrollView.appearance().alwaysBounceVertical = false, but the scroll view still bounces:

Swiping vertically on ScrollView, but still bounces

If I do UIScrollView.appearance().bounces = false, it stops bouncing. However, if I make the rectangle taller than the screen, it also stops bouncing (which I don't want).

Doesn't bounce (yay!) ... but doesn't bounce when the content overflows the screen
Swiping vertically on ScrollView with short rectangle doesn't bounce Swiping vertically on ScrollView with tall rectangle also doesn't bounce

How can I disable bouncing, but only when the content is smaller than scroll view's bounds?


Solution

  • From iOS 16.4 onwards, there is a new modifier for called .scrollBounceBehavior that can be used to prevent ScrollView from bouncing when the content is smalled than the screen.

    Example:

    struct ContentView: View {
        
        var body: some View {
            ScrollView {
                Rectangle()
                    .fill(Color.blue)
                    .frame(height: 300)
                    .padding()
            }
            .scrollBounceBehavior(.basedOnSize)
        }
        
    }