Katafalkas
Katafalkas

Reputation: 993

Custom fonts in Xcode playground

I am writing the interface layout in code. As it is annoying to reload application every time I am testing font size or view layout pixel by pixel, i started doing it in playground. That does help a lot. But I do miss my custom fonts there.

Is there a way to add custom fonts to your playground ?

Upvotes: 18

Views: 5764

Answers (2)

Ali Abbas
Ali Abbas

Reputation: 4277

In addition to Chris Garrett answer, please find the code for Swift 4 :

let cfURL = Bundle.main.url(forResource: "SanaSansAlt-Black", withExtension: "otf")! as CFURL
CTFontManagerRegisterFontsForURL(cfURL, CTFontManagerScope.process, nil)
var fontNames: [[AnyObject]] = []
for name in UIFont.familyNames {
   print(name)
   fontNames.append(UIFont.fontNames(forFamilyName: name) as [AnyObject])
}

Upvotes: 3

Chris Garrett
Chris Garrett

Reputation: 4924

First, add the .ttf file to the resources of your playground. Then you can load the font like this:

let cfURL = NSBundle.mainBundle().URLForResource("Proxima Nova Semibold", withExtension: "ttf") as! CFURL

CTFontManagerRegisterFontsForURL(cfURL, CTFontManagerScope.Process, nil)

let font = UIFont(name: "ProximaNova-Semibold", size:  14.0)

The filename of the .ttf file does not usually match up with the actual desciptor name of the font, which you need for the UIFont name. To find that, open up the .ttf file in Font Book on your mac, look at its details, and look for the PostScript name. That's the name to look for in UIFont(name:...)

Alternatively you can look for your installed font after registering the URL with the following code:

var fontNames: [[AnyObject]] = []
for name in UIFont.familyNames() {
    println(name)
    if let nameString = name as? String
    {
        fontNames.append(UIFont.fontNamesForFamilyName(nameString))
    }
}
fontNames

Upvotes: 27

Related Questions