loading...

Can't use UIFont for Text in SwiftUI

ch3cooh profile image Kenji Wada ・1 min read

I want to specify a font to Text() but UIFont didn't work. What should I do?

Environment

  • Xcode 11.6
  • iOS 13.6

I have a problem!!

I decided to create a utility class like UIFont.futuraMediumFont(ofSize:) to make custom fonts easier to use.

import UIKit

extension UIFont {

    static func futuraMediumFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: "Futura-Medium", size: size) ?? UIFont.systemFont(ofSize: size, weight: .medium)
    }
}

I wanted to use this font as a Text() font as shown below, but a build error occurred.

Text(R.string.localizable.home_title()).font(UIFont.futuraMediumFont(ofSize: 22)

I've solved the problem!

The SwiftUI doesn't use UIFont. Instead, I used the Font class.

import SwiftUI

extension Font {

    static func futuraMedium(size: CGFloat) -> Font {
        return Font.custom("Futura-Medium", size: size)
    }
}

Note

The original article is "SwiftUIで Textのフォント指定にUIFontが使えない". I use machine translation.

Posted on by:

ch3cooh profile

Kenji Wada

@ch3cooh

I'm developing an iOS app and an Android app. Microsoft MVP (2009-2017)

Discussion

pic
Editor guide