SwiftUI - Why is there a default padding on the bottom?

Viewed 106

I'm building a little card view and was adding the text views to it, when I got confused about the padding of the right text "5 / 14". I put 16 into .trailing and .bottom but noticed it was offset. When I changed bottom to 0 it actually looks symmetrical.

How does this happen?

VStack {
            ZStack(alignment: .bottomLeading) {
                Image("sky")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(height:128)
                    .cornerRadius(16)
                
                HStack{
                    Text("Journey")
                        .foregroundColor(Color.white)
                        .font(.title2)
                        .fontWeight(.medium)
                        .multilineTextAlignment(.leading)
                        .padding(.init(top: 0, leading: 24, bottom: 24, trailing: 0))
                    
                    Spacer()
                    
                    Text("5 / 14")
                        .foregroundColor(Color.white)
                        .font(.body)
                        .multilineTextAlignment(.leading)
                        // This padding here, bottom is 0 but looks like 16
                        .padding(.init(top: 0, leading: 0, bottom: 0, trailing: 16))
                }
            }
            .padding(.init(top: 0, leading: 24, bottom: 0, trailing: 24))
        }

screenshot of the result in simulator

1 Answers

It's because your HStack is center-aligned by default.

You can see this by adding .border(_:) to these views:

/* ... */

HStack {
    Text("Journey")
        .foregroundColor(Color.white)
        .font(.title2)
        .fontWeight(.medium)
        .multilineTextAlignment(.leading)
        .padding(.init(top: 0, leading: 24, bottom: 24, trailing: 0))
        .border(Color.red) // <- HERE

    Spacer()

    Text("5 / 14")
        .foregroundColor(Color.white)
        .font(.body)
        .multilineTextAlignment(.leading)
    // This padding here, bottom is 0 but looks like 16
        .padding(.init(top: 0, leading: 0, bottom: 0, trailing: 16))
        .border(Color.blue) // <- HERE
}

Result 1

To fix this issue, just set the HStack's alignment to .bottom.

HStack(alignment: .bottom) {
    /* ... */
    /* Same as before, but now you may want to add the 16 padding again */
}

Result 2

Related