skip to Main Content

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.

2

Answers


  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

    Login or Signup to reply.
  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)
      }
    }  
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search