How to Use iOS Default System Font (SF Pro Text/Display) with Core Text's CTFontCreateWithName

78 views Asked by At

I'm working on an iOS application where I need to render text using Core Text for more precise control over text layout. I want to use the default system font, which I understand is SF Pro Text for text sizes below 20 points and SF Pro Display for sizes 20 points and above. My goal is to ensure that my application matches the system's look and feel as closely as possible, especially in terms of typography.

I'm aware that CTFontCreateWithName requires a font name string, but I'm unsure how to specify SF Pro Text or SF Pro Display dynamically based on text size, considering iOS automatically switches between these two variants.

Here's what I've attempted so far:

let fontSize: CGFloat = 18 // Example size
let fontName = "What should this be?" // How do I specify SF Pro Text or Display dynamically?
let fontRef = CTFontCreateWithName(fontName as CFString, fontSize, nil)

Questions:

  1. What is the correct way to specify the font name for SF Pro Text or SF Pro Display when using CTFontCreateWithName, so it aligns with iOS's automatic font selection based on size?
  2. Is there a recommended approach for dynamically selecting between SF Pro Text and SF Pro Display, or should I directly use one of them for all text sizes?
  3. Are there any considerations or best practices when using the system font with Core Text to ensure my application's typography remains consistent with the rest of the iOS ecosystem?

Any guidance, code snippets, or references to documentation would be greatly appreciated.

1

There are 1 answers

3
Rob Napier On

The correct tool is CTFontCreateUIFontForLanguage. This is not possible with CTFontCreateWithName. The "name" of the default font is ".SFUI-Regular", but you can't actually pass that.

Note that language can be important here, when you know it. There are other SF system fonts, such as SF Arabic, SF Georgian, and others. If you pass NULL, though, it'll use the current system language. (For your use case, trying to match the system as closely as possible, this is likely your best choice.)

As Sweeper points out in the comments, it looks like there's are new Swift overlays to make the syntax a little nicer. I haven't used them, but I'm sure they're wrappers on CTFontCreateUIFontForLanguage.