SwiftUI/UIKit How to convert SwiftUI Font to UIKit UIFont?

Viewed 5239

Due to some limitations in SwiftUI Text. I've to use the UIText instead.

In an UIViewRepresentable,

    func makeUIView(context: Context) -> UITextView {
        let vw = UITextView()
        let env = context.environment
        
        // UIFont?     Font?
        vw.font = env.font

        ...
    }

I want to initialize the UIKit UILabel using the SwiftUI EnvironmentValues.

More specifically, assign an SwiftUI Font to UIKit UIFont.

The question is, how to convert a Font to UIFont?

2 Answers

If you need share same font, then use UIFont as model property and convert in SwiftUI where needed as, for example

Text("Some text")
   .font(Font(uiFont as CTFont))

Create extension:

extension Font {
  init(_ uiFont: UIFont) {
    self = Font(uiFont as CTFont)
  }
}

Use as follows:

Text("Some text")
   .font(Font(yourUIFont))
Related