DEV Community

Kenji Wada
Kenji Wada

Posted on

Can't use UIFont for Text in SwiftUI

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.

Top comments (0)