Both Horizontal and Vertical as well using ScrollView in SwiftUI


Previously I discussed how to create a horizontal and vertical scrolling region using ScrollView. Now in this tutorial, I am going to show you how to apply both horizontal and vertical scrolling together using the same SwiftUI ScrollView.

In order to enable our container to scroll in the vertical direction as well as the horizontal direction, we have to provide both of these directions as you can see in the example below:

ScrollView([.horizontal, .vertical]) {

  // Your content here

}

As you can see, we have set both scroll directions by providing [.horizontal, .vertical]. This can be useful if the content is larger on both sides. For example, if you have a large image and you need to see the details of the image in zooming mode, you have to scroll in both sides.

Now let’s see a complete code example for better understanding:

import SwiftUI


struct ContentView: View {
    
    var body: some View {

        ScrollView([.horizontal, .vertical]) {
            
           VStack(spacing: 36) {
                
                
              ForEach(0..<8) {_ in
                
                HStack {
                    ForEach(0..<4) {
                        Text("Text Item \($0)")
                            .font(.system(size: 28))
                            .padding()
                            .background(.green)
                    }
                }
                
               }
                
                
           }
        }
        .frame(height: 380)
        
        
    }
}

As you can see above, we have created nested ForEach loop inside the VStack to create content that needs to scroll in both vertical and horizontal directions inside the. The outer loop creates a total of 8 HStack and the loop inside HStack creates 4 Text views.