I'm trying to align texts of different sizes at the top so that they stay aligned when the Dynamic Type size changes.
import SwiftUI
struct ContentView: View {
var body: some View {
HStack(alignment: .center, spacing: 0) {
Text("$")
.font(Font.custom("Helvetica", size: 24, relativeTo: .footnote))
.baselineOffset(7)
Text("123")
.font(Font.custom("Helvetica", size: 36, relativeTo: .footnote))
Text("45")
.font(Font.custom("Helvetica", size: 24, relativeTo: .footnote))
.baselineOffset(7)
}
}
}
This is aligned at top at Regular Size
But it loses the top alignment as the Dynamic Type gets bigger: Dynamic Type Size ExtraExtraExtraLarge
Any ideas on how to keep them aligned at top even as the Dynamic Type size changes?
I never needed this kind of configuration but your question arose my curiosity.
(I keep the same context you provided: 3 Text elements with the same text styles/font and two of them having the same font size)
I took a look at the font metrics to understand the returned values.
To reach this goal, I used the alignmentGuide method that returns
a view modified with respect to its horizontal alignment according to the computation performed in the method's closure
by using theascender
andcapHeight
metrics difference.The initial font sizes can be adapted to the user's preferences by using the dynamic property wrapper
@ScaledMetrics
that scales a numeric value.I implement this information with Xcode 13.4 and iOS 15:
Following this rationale, I get the following result to keep texts of different sizes aligned at top as the dynamic type size changes.
Don't hesitate to adapt this code snippet that fits the example you provided and that's definitely not generic.