SwiftUI ScrollView

ScrollView is a view that allows for scrolling through multiple child elements/views, such as Text, Images, Stacks, etc. Basic Code Example The content of a ScrollView can be a simple Text element as shown above, or it can be other views such as custom views and Stacks. The example above will have the default ScrollView… View Article
Written by

Chris C

Updated on

May 01 2024

Table of contents

    ScrollView is a view that allows for scrolling through multiple child elements/views, such as Text, Images, Stacks, etc.

    Basic Code Example

    ScrollView {
      Text("Hello world!")
    }

    The content of a ScrollView can be a simple Text element as shown above, or it can be other views such as custom views and Stacks. The example above will have the default ScrollView settings, so it will be scrollable vertically and there will be a scroll bar indicator on the side to show scroll progress.

    Changing the Scroll Direction

    ScrollView (.horizontal) {
      HStack {
        ForEach(0..<10) { index in 
          Text("\(index)")
        }
      }
    }
    
    ScrollView ([.horizontal, .vertical]) {
      HStack {
        ForEach(0..<10) { index in 
          Text("\(index)")
        }
      }
    }

    ScrollView takes in axes parameters to specify the scroll direction. By passing in .horizontal such as in line 1, the view will now scroll horizontally rather than vertically.

    The ScrollView can also be scrollable both horizontally and vertically, which is shown in line 9.

    Visibility of the Scroll bar Indicator

    ScrollView (.horizontal, showsIndicators: false) {
      HStack {
        ForEach(0..<10) { index in 
          Text("\(index)")
        }
      }
    }
    

    The showsIndicators parameter in line 1 takes in true or false to show or hide the scroll bar indicator respectively. The default setting is true.



    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris