0

Text of different font sizes

I have 2 Text elements in a VStack. They are set to different font size.

How do I get the first glyph of the 2 Text elements to align perfectly left? Is that even possible?

Below is the code snippet:

extension Font {
    static let countDownTitle: Font = Font.system(size: 46, weight: .regular, design: .rounded).leading(.tight)
}

struct MyView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Hello!!")
            Text("20.49").font(.countDownTitle)
        }
     }
}
billibala
  • 321
  • 4
  • 14

1 Answers1

1

You have a bit of an artificial test going on here. Remember, each character takes up a different amount of room in a proportional font takes up a different amount of room. When they are laid out, they are put in a space that is controlled by the font designer, not us. You can see this is you cycle through different numbers. The 4 is pretty much right on, but the 5 is way off. This is one of those things that your ability to control it is lacking.

While, I am not at all recommending this, you could get perfect alignment like this, using a monospaced font and an .offset():

extension Font {
    static let countDownTitle: Font = Font(UIFont.monospacedSystemFont(ofSize: 46, weight: .regular))
}

struct MyView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Hello!!")
            Text("50.49").font(.countDownTitle)
                .offset(x: -2.2, y: 0)
        }
     }
}

But, this is really ugly.

Yrb
  • 8,103
  • 2
  • 14
  • 44
  • Appreciate your help @yrb. Agree, it's ugly. But it seems like `.offset()` or `.alignmentGuide()` are the only solution. I tried out `Text.tracking()` but that's not helping. – billibala Nov 13 '21 at 09:36
  • `.offset()" is only going to work on monospaced fonts. On a proportional, unless you have an individual offset for each digit, they will be off somewhere. – Yrb Nov 13 '21 at 18:14