skip to Main Content

This is my code to create HStack with equal width elements for full width parent View:

HStack(alignment: .center, spacing: 0) {
    ForEach(0...6, id: .self) { _ in
        Color(UIColor.white.withAlphaComponent(0.1))
            .cornerRadius(5)
            .padding(2)
            .frame(minWidth: 0, maxWidth: .infinity)
            .frame(minHeight: 0, maxHeight: .infinity)
    }
}
.frame(minWidth: 0, maxWidth: .infinity)
.frame(height: 70)

and the effect is:

enter image description here

But now I need to add the center "T" text inside every View at the top, so I simply replace Color view with VStack view and:

HStack(alignment: .center, spacing: 0) {
    ForEach(0...6, id: .self) { _ in
        VStack(alignment: .center) {
            Text("T")
        }
        .background(Color(UIColor.white.withAlphaComponent(0.1)))
        .cornerRadius(5)
        .padding(2)
        .frame(minWidth: 0, maxWidth: .infinity)
        .frame(minHeight: 0, maxHeight: .infinity)
    }
}
.frame(minWidth: 0, maxWidth: .infinity)
.frame(height: 70)

and the effect is wrong. Why?

enter image description here

What to do to keep size of the rectangle views with "T", as it was without "T"?

2

Answers


  1. I think you want scaledToFill() on both the VStack and the HStack:

    HStack(alignment: .center, spacing: 0) {
        ForEach(0...6, id: .self) { _ in
            VStack(alignment: .center) {
                Text("T")
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color(UIColor.white.withAlphaComponent(0.1)))
            .cornerRadius(5)
            .padding(2)
            .scaledToFill()
        }
    }
    .frame(maxWidth: .infinity, idealHeight: 70)
    .scaledToFill()
    

    enter image description here

    And where the .frame() is set does make a difference as pointed out by @timbre

    Login or Signup to reply.
  2. Here you want to use an overlay for what your are trying to achieve:

            HStack(alignment: .center, spacing: 0) {
                ForEach(0...6, id: .self) { _ in
                    Color(UIColor.red.withAlphaComponent(0.1))
                        .overlay {
                            Text("T")
                        }
                        .cornerRadius(5)
                        .padding(2)
                }
            }
            .frame(height: 70)
    

    Yout don’t need .frame(minWidth: 0, maxWidth: .infinity) modifier since Color by default already takes up all the space available. If you don’t want any color in the background set it to .clear.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search