Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In iOS, Is it possible to add a font to the app during runtime?

In my app I want to let the user download and use fonts, but I don't know how to do this dynamically. I know we have to specify the fonts we want to use in the app's Info.plist file, but we can't add anything to that plist file programmatically. There is zynga's library but it is a subclass of UILabel.

Please help

like image 703
Virat Naithani Avatar asked Mar 22 '12 11:03

Virat Naithani


2 Answers

Yes, it is possible:

/**
 Downloads a `.ttf` file from an URL and creates an UIFont.
 
 - Parameter url: The URL of the `.ttf` file.
 
 - Precondition: The URL Session must be previously configured at ease.
 */
fileprivate func setFont(url: URL) {
    // Download the font file in .ttf format.
    dataTask = urlSession?.dataTask(with: url,
                                    completionHandler: { [weak self] (data, response, error) in
        guard error == nil,
            let data = data,
            (response as? HTTPURLResponse)?.statusCode == 200,
            // Create a Font Descriptor from the raw data.
            let ctFontDescriptor = CTFontManagerCreateFontDescriptorFromData(data as CFData) else {
                // Error during the download of the .ttf file.
                self?.error()
                return
        }
        // Create CTFont from the Font Descriptor and convert it to UIFont.
        let font: UIFont = CTFontCreateWithFontDescriptor(ctFontDescriptor, 0.0, nil) as UIFont
        // Do whatever you want with the UIFont :)
        self?.success(font: font)
    })
    dataTask?.resume()
}

With this code, you can download a .ttf file from the Internet (you could get the file from any other source) containing a font and use it as UIFont.

like image 191
Sergio Avatar answered Nov 14 '22 08:11

Sergio


You could use CGFontCreateWithDataProvider() followed by CTFontCreateWithGraphicsFont(). Then you'd have a CTFont, which you can draw using Core Text.

As far as I know there's no way to get a UIFont from a custom font without either having the font in your app bundle and using the Info.plist method (i.e. not downloading it), or using private APIs.

like image 38
Amy Worrall Avatar answered Nov 14 '22 07:11

Amy Worrall