'SwiftUI Custom ScrollView - HStack wider than screen

If I have a view like this:

HStack {
  ForEach(0..<10) { i in
    Text("Item \(i)").frame(width: 200, height: 200).background(.red)
  }
}

The HStack has a wider width than the screen, and the content shown is center-aligned. That is to say, I can see "Item 4" and "Item 5" on-screen. Is there a way to tell SwiftUI in this case to align the extra-wide view such that the left edge of the view is at the left edge of the screen? I.e., I see "Item 0" and "Item 1" instead of 4 and 5.

The motivation is building a ScrollView with some fancy functionality.

One way to resolve this is to wrap it inside GeometryReader. That's not ideal, since it requires the vertical height to be explicitly specified.



Solution 1:[1]

A possible approach is to give a container for alignment (because by default the view is centered)

    Color.clear.overlay(   // << like clip view actually
        HStack {
            ForEach(0..<10) { i in
                Text("Item \(i)").frame(width: 200, height: 200).background(.red)
            }
        }
    , alignment: .leading)   // << here !!
    .frame(maxWidth: .infinity, maxHeight: 200)

demo

Solution 2:[2]

The issue is you are giving fixed width that causes the issue. You can remove width:

HStack {
  ForEach(0..<10) { i in
    Text("Item \(i)").frame(height: 200).background(.red)
  }
}  

Or you can use:

HStack {
  ForEach(0..<10) { i in
    Text("Item \(i)").frame(maxWidth: valueYouWant, maxHeight: valueYouWant).background(.red)
  }
}  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asperi
Solution 2 Taimoor Arif