I am using Xcode 12.4 with Swift 5.4 on macos 11.2.2
I want to control the space between two Text
views. Naturally, padding
comes to mind. Here's the code
VStack(alignment: .leading) {
Text("Exploring San Francisco")
.font(.appTitle1)
.fontWeight(.bold)
.padding(.bottom, 0)
Text("May 1, 2021 - May 5, 2021")
.font(.appSmallBody)
.fontWeight(.bold)
.textCase(.uppercase)
.foregroundColor(.init(hex: "666666"))
}
Note that I explicitly write bottom padding is 0px. And here's the result:
Now if I want 1px padding between them, the padding would become too large. Here's the result of bottom padding of 1 px:
As you could probably tell, the distance between them is definitely not 1px, but more like 10px.
However, if I increase the padding to 2px, you could barely see the difference between 1px and 2px:
Why is the padding distance inconsistent?
The only workaround I found is removing the padding
and use the VStack
's spacing
parameter:
VStack(alignment: .leading, spacing: 1) {
Text("Exploring San Francisco")
.font(.appTitle1)
.fontWeight(.bold)
Text("May 1, 2021 - May 5, 2021")
.font(.appSmallBody)
.fontWeight(.bold)
.textCase(.uppercase)
.foregroundColor(.init(hex: "666666"))
}
But this is not ideal when there're multiple views in the stack and I want to customize the distance between each pair of them.
Is this a SwiftUI bug? Is there a more elegant workaround for this issue? Thanks!
You can try and do the following: basically declare spacing: 0 on the vstack and then change the padding and it will behave the way you want.
VStack(alignment: .leading, spacing: 0) {
Text("Exploring San Francisco")
.font(.title)
.fontWeight(.bold)
.lineLimit(1)
Text("May 1, 2021 - May 5, 2021")
.font(.subheadline)
.fontWeight(.bold)
.textCase(.uppercase)
.foregroundColor(Color.gray)
.padding(.top, 1)
}
changing the last line in the example you can see the difference from
.padding(.top, 0)
.padding(.top, 1)
.padding(.top, 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With