Exploring SwiftUI: baselineOffset Modifier
Book

Exploring MusicKit and Apple Music API

Unlock the full power of MusicKit & Apple Music APIs in your apps with the best guide! Use code musickit-blog for a limited-time 35% discount!

I was trying a new custom font for Chroma Game, and for the first time, I saw that the font was being cut from the bottom. This happened for all the Text elements using the new custom font.

After searching, I realized that it happens with subscript characters, too, for specific custom fonts. It looks like SwiftUI cannot properly calculate the vertical size of the label.

baselineOffset method

From this answer on the developer forums, I found out about the baselineOffset(_:) modifier. The documentation describes it as:

Sets the vertical offset for the text relative to its baseline.

The parameter accepts a CGFloat value which is the amount you can shift the text vertically relative to its baseline.

You can fix alignment issues or custom label designs with different labels at a different offset.

After trial and error, I found out that 1 is the least amount to offset. This moves the text vertically upwards while the label remains intact. To anti-offset (!) this offset, so it doesn’t look uneven, I added padding at the top of value 1.

The view now looks like this:

struct OffsetText<S>: View where S: StringProtocol {
    private var content: S
    private var font: CustomFont
    
    init(_ content: S, font: CustomFont) {
        self.content = content
        self.font = font
    }
    
    var body: some View {
        Text(content)
            .font(font)
            .baselineOffset(1)
            .padding(.top, 1)
    }
}

If you want, for larger offsets, you can make the value scale relative to a particular font as well. For example:

  @ScaledMetric(relativeTo: .body) var baselineOffset = 1

As you increase or decrease the font size, the offset also reacts to it and adjusts relatively instead of using a constant value.

Conclusion

For any misalignment of texts, you can use the baselineOffset modifier and experiment with the value to your satisfaction.

Tag @rudrankriyam on Twitter if you have already implemented something similar!

Thanks for reading, and I hope you’re enjoying it!

Book

Exploring MusicKit and Apple Music API

Unlock the full power of MusicKit & Apple Music APIs in your apps with the best guide! Use code musickit-blog for a limited-time 35% discount!

Written by

Rudrank Riyam

Hi, my name is Rudrank. I create apps for Apple Platforms while listening to music all day and night. Author of "Exploring MusicKit". Apple WWDC 2019 scholarship winner.