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.

1
  • Can this prob help you ? sweettutos.com/… Commented Jan 25, 2023 at 15:34

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 stackoverflow.com/a/62451599/12299030.
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)
  }
}  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.