ScrollView in SwiftUI is a container view that makes its content scrollable. It makes it easier to create scrolling containers of views.
With the help of using ScrollView, we can both create vertical and horizontal scrolling regions. In our example, we will create 10 Text views dynamically using the ForEach loop. These will work as scrolling items. This way, we don’t have to create Text view 10 times.
For vertical scrolling, we have to specify the .vertical
axes. On the other hand, we can use the .horizontal
for horizontal scrolling.
By default, a scroll view will always work as vertical scrolling in SwiftUI. That means, even if we don’t specify axes, it will always scroll vertically.
Let’s see an example of using the ScrollView to create vertical scrollable content:
ScrollView {
VStack(spacing: 36) {
ForEach(0..<10) {
Text("Text Item \($0)")
.font(.system(size: 28))
.padding()
.background(.green)
}
}
}
.frame(height: 380)
As you can see in the above code, I have set the height to 380. So the container height is 380 and all content is scrollable within this height. If you want, you can specify the axes:
ScrollView(.vertical)
But it will work as same.
In order to scroll the content of ScrollView horizontally, we have to pass .horizontal
. Below is an example of horizontal scrolling using ScrollView in SwiftUI:
ScrollView(.horizontal) {
HStack {
ForEach(0..<10) {
Text("Text Item \($0)")
.font(.system(size: 28))
.padding()
.background(.green)
}
}
}
It is possible to apply scrolling in both vertical and horizontal directions. To achieve this, you have to pass the parameter [.horizontal, .vertical]
to the ScrollView
. Below is given the syntax:
ScrollView([.horizontal, .vertical]) {
// Some Items
}
To see the full tutorial for scrolling in both directions, read this tutorial – Both Horizontal and Vertical as well using ScrollView in SwiftUI.