如何在 Xcode playgrounds 中实现自定义字体

How to implement custom font in Xcode playgrounds

我想用自定义字体更改标签的字体,但编译器给我一个问题: 在展开 Optinal 值时意外发现 nil。 我认为这个问题是由于 Xcode 无法识别我的字体文件 Brandon_reg.otf。我做错了什么?下载游乐场: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

您的字体文件中没有名为 "horrendo" 的字体。这对我有用:

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