简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM