Search code examples
swifttextviewswiftui

How to remove space above and below text view in SwiftUI?


I have a text with a size of 80. When I put a border on this view, I see that there is additional space above and below the text. To save space in my application, I need to remove this space. But I don't know if it's possible properly?

Exemple of code:

import SwiftUI

struct ContentView: View {
  var body: some View {
    Text("360°")
      .font(Font.system(size: 80, weight: .thin, design: .default).monospacedDigit())
      .border(Color.red, width: 2)
  }
}

The result:

Screen result

I need the green result:

Screen result I need


Solution

  • The vertical space is occupied by the Text itself. Adding fixed negative padding isn't recommended. Use this, only if both text and font are hardcoded.

    Text("360°")
        .font(Font.system(size: 80, weight: .thin, design: .default).monospacedDigit())
        .padding(.vertical, -18)
        .border(Color.red, width: 1),
    

    Output