Search code examples
swiftfontsios13xcode11

How to load iOS 13 default font using font name?


I have a strange problem with iOS 13 system font. I am trying to load iOS default font San Francisco using the font name. But due to some iOS bug it's loading some other font like Times New Roman. I saw few problems like this here and here. But in my case I have to load the font with name because I am using a Utility class to globally set font name in app delegate. Is there any way to load the system font using font name in iOS 13?

// Set font here
 MUIConstats.shared.defaultFontRegularName = UIFont.systemFont(ofSize: 17).fontName


 // Get font from here

 class func appFontRegularOf(size: CGFloat)-> UIFont{


        if let fontName = MUIConstats.shared.defaultFontRegularName {
            return UIFont(name:fontName, size: size) ?? UIFont.systemFont(ofSize:size)
        }else{
            return  UIFont.systemFont(ofSize:size)
        }

    }

Solution

  • You can store the name of a nonsystem font, but if it's the system font the only thing you're allowed to store is the fact that it's the system font. This is a perfect opportunity for a union:

    enum WhatFont {
        case system
        case name(String)
        func fontOfSize(_ sz:CGFloat) -> UIFont? {
            switch self {
            case .system: return UIFont.systemFont(ofSize: sz)
            case .name(let name): return UIFont(name: name, size: sz)
            }
        }
    }
    

    Test it:

    let f1 = WhatFont.system
    print(f1.fontOfSize(17))
    let f2 = WhatFont.name("Georgia")
    print(f2.fontOfSize(17))