Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading and installing a custom font in iOS [duplicate]

Tags:

ios

swift

uifont

I have searched here for the answer to this but I haven't found any posts that I can use to get an answer. I have only found answers about pre-installing the font to the plist of the app which won't work for me.

What I am trying to do is download a Font from a URL, store the file locally to the app and then install or use that font in controls.

I am at the point of installing the font to the tablet to use. I can add it to CTFontManager without any issues using the code below.

private func InstallFont(dest:String)
{
    let fontData = NSData(contentsOfFile: dest)!

    let dataProvider = CGDataProviderCreateWithCFData(fontData)
    let cgFont = CGFontCreateWithDataProvider(dataProvider)!

    var error: Unmanaged<CFError>?
    if !CTFontManagerRegisterGraphicsFont(cgFont, &error)
    {
        print("Error loading Font!")
    }
}

The issue that I am facing is that I cannot seem to find the font I have installed anywhere in the app, I have tried to set it like below but just goes to default which tells me it can not be found.

self.font = UIFont(name: "Font Name", size: 20.0)

I have also looped through the font family's to see if it has been installed and no success there either.

for x in UIFont.familyNames()
{
    print(x)

    for z in UIFont.fontNamesForFamilyName(x)
    {
        print("== \(z)")
    }
}

Is what I am trying to achieve even possible? If so what am I doing wrong?

like image 988
BunkerBilly Avatar asked Dec 01 '15 11:12

BunkerBilly


2 Answers

It is possible. I created an example project in github. You have to just add the line below.

if !CTFontManagerRegisterGraphicsFont(cgFont, &error)
{
    print("Error loading Font!")
}
else
{
    let fontName = CGFontCopyPostScriptName(cgFont)
    uiFont = UIFont(name: String(fontName) , size: 30)
}

Thank you for Michael Dautermann, he was right.

Github project link

enter image description here

like image 111
Gyuri T Avatar answered Oct 01 '22 06:10

Gyuri T


According to the answers in this related question, you should be able to download your font and register it the way you are already doing (which it sounds like you are doing correctly), but you simply need to get the Postscript name and use that to create a corresponding UIFont:

var uiFont : UIFont?
let fontData = NSData(contentsOfFile: dest)!

let dataProvider = CGDataProviderCreateWithCFData(fontData)
let cgFont = CGFontCreateWithDataProvider(dataProvider)!

var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(cgFont, &error)
{
    print("Error loading Font!")
} else {
    let fontName = CGFontCopyPostScriptName(fontRef)
    uiFont = UIFont(name: fontName, size: 30)
}
like image 41
Michael Dautermann Avatar answered Oct 01 '22 07:10

Michael Dautermann