I'm creating new app and in that I've to use custom fonts. I'm also planning to support dynamic font types. That's why I'm creating common structure which will provide me fonts at different places of application. For that I've written following code.
static func getHeaderFont(forStyle style: UIFont.TextStyle) -> UIFont {
guard let font = UIFont(name: "Montserrat-SemiBold", size: UIFont.systemFontSize) else { fatalError("No font found") }
return UIFontMetrics(forTextStyle: style).scaledFont(for: font)
}
For this I'm following this guide
But whatever style I pass to this function I always get same font-size and style.
Here is screenshot of my testing.
I've tried to get font-size for title2, headline, body, caption2. What I'm doing wrong here?
Your function will return different results - it just so happens that the dynamic type size of your phone is the default (standard) size, so everything is scaled by a factor of 1 (aka no change at all).
If you change your dynamic type size in the settings app, you will see that e.g.
.caption1and.extraLargeTitleare scaled differently. If you change it to a larger size,.extraLargeTitlewill not change much, but.caption1would be a lot larger, because captions are usually smaller than "extra large titles" :DI think you misunderstood what the purpose of
UIFontMetricsis. It is not for determining the suitable font size for a text style (you should determine this yourself), but for determining how much to scale an existing font, based on the dynamic type size setting and text style.When the dynamic type size is the default setting, no scaling is needed, and you will always get the same font size you passed in (in this case,
UIFont.systemFontSize).When the dynamic type size setting changes, different
TextStyles are scaled differently - that's what theforTextStyleparameter is for.If you want your font's font size to always match the system fonts for a given
TextStyle(not recommended), see the specification here. Take the sizes in the "Large (Default)" column, and use that instead ofUIFont.systemFontSizein your code.If you use a custom font, it is natural to also design your own font sizes for each text style, and not rely on the ones designed for the system font. While the ones for the system font looks good on the system font, it might not be suitable for your custom font.