How to add custom fonts to an iPhone app?

前端 未结 2 1226
情书的邮戳
情书的邮戳 2020-11-28 14:35

What must I do to get an UIFont object with a custom font? I remember there was also something going on in the Info.plist file.

What font file formats are supported?

2条回答
  •  失恋的感觉
    2020-11-28 15:07

    Programming way (Swift)

    Add the fonts to your project at the resource folder
    And add this function:

    func loadFont(filePath: String) {
    
        let fontData = NSData(contentsOfFile: filePath)!
    
        let dataProvider = CGDataProviderCreateWithCFData(fontData)
        let cgFont = CGFontCreateWithDataProvider(dataProvider)!
    
        var error: Unmanaged?
        if !CTFontManagerRegisterGraphicsFont(cgFont, &error) {
            let errorDescription: CFStringRef = CFErrorCopyDescription(error!.takeUnretainedValue())
            print("Unable to load font: %@", errorDescription)
        }
    }
    

    Use example:

    if let fontPath = NSBundle.mainBundle().pathForResource("MyCustomFont", ofType: "ttf") {
        loadFont(fontPath)
    }
    
    let myFont = UIFont(name: "MyCustomFont", size: CGFloat(18))
    

提交回复
热议问题