Exploring Freelancing
Navigate freelancing as a developer; find clients, manage contracts, ensure timely payment, and learn from experiences!
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!
Exploring Freelancing
Navigate freelancing as a developer; find clients, manage contracts, ensure timely payment, and learn from experiences!