14

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?

zrfrank
  • 2,631
  • 1
  • 12
  • 18

2 Answers2

23

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))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • I think this is a valid solution, though, if we go this route, all SwiftUI EnvironmentValues that related to Font should be manually overridden. So that both the SwiftUI and UIKit part using the unified UIFont. – zrfrank Oct 15 '20 at 10:50
  • It's bit off-topic, would you think there is a way that using "attributed text" or something alike in SwiftUI without go though UIKit/Appkit? – zrfrank Oct 15 '20 at 10:54
  • If *attributed text* is not very complex then consider https://stackoverflow.com/a/59531328/12299030 – Asperi Oct 15 '20 at 11:14
  • without UIKit, if we go the `Text + Text` route, we'll need a builder that parse the attributed text and built it into `Text.someModifers + Text...`. Maybe for the moment UIKit is the best choice :-). – zrfrank Oct 15 '20 at 13:05
  • 1
    @Asperi The solution works on paper, but in this case `Font` stops being scalable for content size categories, even if I pass the dynamic `.preferredFont(forTextStyle: .headline)` as an initial `UIFont`. Any suggestions for this usecase? – demon9733 Mar 12 '22 at 01:22
  • This isn't really a solution to the question as asked - it's a concession to the shortcomings of SwiftUI. Good work-around, though. – Grimxn May 30 '23 at 09:46
-2

Create extension:

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

Use as follows:

Text("Some text")
   .font(Font(yourUIFont))
Andrew Stoddart
  • 408
  • 4
  • 9