Home > Enterprise >  SwiftUI ZStack alignment is not working as expected
SwiftUI ZStack alignment is not working as expected

Time:12-13

enter image description here

The green box needs to be aligned almost all the way to the left with a 0.4 padding, but it doesn't I've tried replacing the outer ZStack with HStack or VStack and still no luck. The label on the right is the padding I'm applying

ZStack(alignment: .leading) {
    ZStack {}
        .padding(.leading, x)
        .frame(width: width)
        .frame(maxHeight: .infinity)
        .background(Color.green)
}
.frame(maxWidth: .infinity)
.background(Color.gray.opacity(0.1))
.frame(height: 8)

CodePudding user response:

instead of nesting two ZStacks, you could try using two Rectangle objects inside a ZStack.

I tried and it worked for me.

The stacks usually contain something, if they don't, I think it would be better to use objects such as rectangles and such.

    ZStack(alignment: .leading) {
        Rectangle()
            .fill(Color.green)
            .padding(.leading, x)
            .frame(width: width)
        
        Rectangle()
            .fill(Color.gray.opacity(0.1))
            .frame(maxWidth: .infinity)
    }
    .frame(height: 8)
  • Related