A scroll view is a scrollable component in SwiftUI. It is a container view that displays its content in a horizontal or vertical scrolling direction. It does not allow zooming in or out of the content.
Scroll views are an essential component in SwiftUI that allows users to view content that is larger than the visible area of the screen.
To support scrollable content SwiftUI provides a view called ScrollView. When content is inside a ScrollView, the content becomes scrollable. To achieve this you just need to put the content you want to make scrollable inside a ScrollView. By doing this the views become scrollable.
In the following example we can see the use of ScrollView:
struct ContentView: View {
var body: some View {
ScrollView {
VStack(spacing: 10) {
ForEach(0..<20) {
Text("Post \($0)")
.foregroundStyle(.white)
.font(.largeTitle)
.frame(width: 150, height: 150)
.background(.blue)
}
}
}
.frame(height: 350)
.font(.largeTitle)
}
}
How to add horizontal ScrollView
A scroll view is vertical by default, however it also supports horizontal scrolling content. In the following example you can see a horizontal ScrollView:
struct ContentView: View {
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 10) {
ForEach(0..<20) {
Text("Post \($0)")
.foregroundStyle(.white)
.font(.largeTitle)
.frame(width: 150, height: 150)
.background(.blue)
}
}
}
.frame(height: 350)
.font(.largeTitle)
}
}
The first thing we do is pass the .horizontal value to ScrollView.
Since we are using horizontal scrolling we have to change the stack view from VStack to HStack.
After making these changes you will notice that they are now arranged horizontally and now are scrollable.
Hiding the Scroll indicator
While you are scrolling through the views you may have noticed that there is a scroll indicator near the bottom of the screen. This indicator is shown by default.
If you want to hide it all you have to do is change the ScrollView by adding showsIndicators: false as in this example:
struct ContentView: View {
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 10) {
ForEach(0..<20) {
Text("Post \($0)")
.foregroundStyle(.white)
.font(.largeTitle)
.frame(width: 150, height: 150)
.background(.blue)
}
}
}
.frame(height: 350)
.font(.largeTitle)
}
}
By setting showsIndicators to false, iOS will no longer show the indicator.