1

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.

CaptainStiggz
  • 1,787
  • 6
  • 26
  • 50
  • Can this prob help you ? https://sweettutos.com/swiftui-scrollview-how-to-make-an-onboarding-slideshow-for-your-app/ – Malloc Jan 25 '23 at 15:34

2 Answers2

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

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • This is great, but you still have to specify the height of the container, right? Similar to the `GeometryReader`, since this is an overlay, you need to tell the container what its height should be. Not IDEAL, but workable. – CaptainStiggz Apr 22 '22 at 15:55
  • Well, actually detectable height is a different question, but you can always detect it dynamically and transfer to parent by preferences to limit container height. See this one for example https://stackoverflow.com/a/62451599/12299030. – Asperi Apr 22 '22 at 16:03
0

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)
  }
}  
Taimoor Arif
  • 750
  • 3
  • 19