Reading time: 1 min

This recipe shows how to handle conversions between UIKit UIFont and SwiftUI Font, as there are more than a few instances where using both is necessary. This mainly comes into play when you import UIViews into SwiftUI via UIViewRepresentable.

OK, so here's how it is:

  • Converting UIFont to Font is easy. It's a bit surprising that Apple hasn't made this a part of SwiftUI framework already, given how little straightforward code is involved:
public extension Font {
  init(uiFont: UIFont) {
    self = Font(uiFont as CTFont)
  }
}

Then, you can use it like this:

var body: some View {
  Text("Some text")
    .font(Font(uiFont: UIFont.systemFont(ofSize: 12)))
}
  • On the other hand, you can't convert Font to UIFont. If you look at Font's interface in the SwiftUI Framework, you'll see that it's kind of a black box - you can't get any info out of it, just add more modifiers. Because of this, it's best to hold all app fonts as UIFonts, and then convert them to Fonts when necessary. In other words, you might have a Fonts.swift file whose content is something like this:
let regularUIFont = UIFont(name: "Lato-Regular", size: 18)!
let thinUIFont = UIFont(name: "Lato-Thin", size: 14)!

let regularFont = Font(uiFont: regularUIFont)
let thinFont = Font(uiFont: thinUIFont)

It's a bit ugly since it forces you to hold duplicates, but there's no other way to assure that you'll be able to use a Font as a UIFont when necessary.

Next Post Previous Post