Search code examples
iosswiftxcodefontsswift-playground

How to implement custom font in Xcode playgrounds


I want to change the font of a label with a custom font, but the compiler is giving me an issue: Unexpectedly found nil while unwrapping an Optinal value. I think that this issue is due to Xcode not recognizing my font file, Brandon_reg.otf. What did I do wrong? Download Playground: https://ufile.io/940cc

import UIKit 
import PlaygroundSupport

var view = UIView(frame: UIScreen.main.bounds)

let fontURL = Bundle.main.url(forResource: "Brandon_reg", withExtension: "otf")
CTFontManagerRegisterFontsForURL(fontURL! as CFURL, CTFontManagerScope.process, nil)
var font = UIFont(name: "horrendo", size: 30)
var attrs = [NSFontAttributeName : font!,
             NSForegroundColorAttributeName : UIColor.white,
             NSBaselineOffsetAttributeName : 0.0] as [String : Any]
let nameAttrSring = NSAttributedString(string: "Brandon_reg", attributes: attrs)

let mainLabel: UILabel = {
    let label = UILabel()
    label.font = font
    label.textColor = .white
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    label.numberOfLines = 0
    return label
}()

view.addSubview(mainLabel)
PlaygroundPage.current.liveView = view
PlaygroundPage.current.needsIndefiniteExecution = true

Solution

  • Your font file does not have a font named "horrendo" in it. This works for me:

     var font = UIFont(name: "Brandon Grotesque", size: 30)