Disable ScrollView bounce In SwiftUI
In this tutorial, we will see how to disable ScrollView bounce in SwiftUI.
The ScrollView has a bounce behavior by default. That means when we reach the edge of the ScrollView, it bounces back.
But SwiftUI doesn’t provide any built-in modifier to disable the bounce. So, we can simply call the init()
at the top of the body
view and add the following code to achieve our task.
init() { UIScrollView.appearance().bounces = false }
In the above code, I have set the bounces
property to false
to disable the bouncing effect. So, when we scroll to the end of the content, the scroll view stops without bouncing back.
Create a simple ScrollView
First of all, I will create a simple scroll view using the ScrollView
property to see what kind of bouncing it applies by default when I reach the edge of the ScrollView
.
Example
import SwiftUI struct ContentView: View { var body: some View { ScrollView { ForEach(0..<20) { index in Text("Option \(index)") .font(.title) .padding() } } } }
As you can see in the above code, I have set up a scrollable list of text items using a ScrollView
and ForEach
loop.
Output:
Disable ScrollView bounce
We can call the init()
function at the top of the body view and use the UIScrollView.appearance().bounces = false
property to disable the bounce of the ScrollView
.
Example
import SwiftUI struct ContentView: View { // Disable bounce globally for all ScrollViews init() { UIScrollView.appearance().bounces = false } var body: some View { ScrollView(showsIndicators: false) { ForEach(0..<20) { index in Text("Option \(index)") .font(.title) .padding() } } } }
In the above program, I have used the init()
function to configure the appearance of the UIScrollView
globally within our SwiftUI view, and I have set bounces
to false
to disable the bounce effect for the ScrollView.
Output:
Disable ScrollView bounce using the onAppear modifier
We can disable bouncing for the ScrollView
using UIScrollView.appearance().bounces = false
within the onAppear
modifier and applying this modifier to a specific ScrollView
.
Example
import SwiftUI struct ContentView: View { var body: some View { ScrollView(showsIndicators: false) { ForEach(0..<20) { index in Text("Option \(index)") .font(.title) .padding() } } // To disable ScrollView bouncing .onAppear { UIScrollView.appearance().bounces = false } } }
Output:
Leave a Reply