SwiftUI Text unexpected padding bottom and top

Viewed 645

I need precise control over the area taken by Text. I created the most basic program that shows unexpected top and bottom spacing being added to a text. Where is this extra padding coming from? How to get rid of it?

@main struct myApp: App {

init() {    }

var body: some Scene {
    WindowGroup {
        Text("80")
            .font(.system(size: 30, weight: .bold, design: .default))
            .background(Color.red)
    }
}

}

enter image description here

2 Answers

Text seems to have default padding as seen here

enter image description here

You can get past that by adjusting the padding to a negative amount

Replace your code with this

Text("80")
        .font(.system(size: 30, weight: .bold, design: .default))
        .padding(.vertical, -6)
        .background(Color.red)

Here is a solution if you want to make it dynamic

  struct TestView: View {
    var fontSize: CGFloat = 110
    var paddingSize: CGFloat {
        -(fontSize * 0.23)
    }
    var body: some View {
        Text("80")
            .font(.system(size: fontSize, weight: .bold, design: .default))
            .padding(.vertical, paddingSize)
            .background(Color.red)
        Text("Hello")
    }
}

So even with a large font size of 110 like in the picture you can render it how you like enter image description here

You'll need to tweak the multiplier how you see fit

Turns out that the padding top and bottom is actually not there at all. In my example with numbers this looks like wasted space, but actually certain characters do need this room as can be seen on this picture: enter image description here

Since I am only going to show numbers I have used the solution by @Sergio to correct for this overspace.

Related