How to add SwiftUI scrollview for horizontal and vertical scrolling

SwiftUI ScrollView is a container view that allows users to scroll through a collection of views vertically, horizontally, or in both directions. It provides a way to display content that exceeds the available screen space, enabling users to view all the content by scrolling.

Key features of SwiftUI’s ScrollView include:

  1. Scroll Direction: ScrollView can be configured to scroll vertically, horizontally, or both, depending on the layout requirements of your app.
  2. Dynamic Content: It supports dynamic content, meaning you can add or remove views dynamically within the ScrollView, and it adjusts its scrolling behavior accordingly.
  3. Customization: ScrollView provides various customization options, such as content alignment, scroll indicators, and insets.
  4. Performance Optimization: SwiftUI’s ScrollView is designed to efficiently handle large amounts of content while maintaining good performance.

Vertical ScrollView

To create a vertical scroll view, use the following code snippet:

In this example:

  • By default ScrollView has .vertical parameter for vertical scrolling. If we want to scroll only in vertical direction then we do not need to provide it as a parameter.

Horizontal ScrollView

To add a horizontal ScrollView in SwiftUI, you can use the .horizontal parameter within the ScrollView initializer.

By default scrollview adjusts its height according to the views added inside it. In this horizontal scrollview example its height will be 100. But you can change its height using frame modifier. Let us set the height equal to 400 and background colour to green so we can observe height of scrollview.

Scrolling Vertically and Horizontally

To enable scrolling on both horizontally and vertically, you can use a single ScrollView and allow it to scroll in both directions by setting its axes parameter to .horizontal and .vertical.

Hide ScrollView’s Indicators

If you want to hide the scroll indicators on scrolling, you can do it by simply providing parameter showIndicators: false like