swiftuiswiftui-text

SwiftUI Text unexpected padding bottom and top


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


Solution

  • 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