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

时间:2022-08-13 23:10:43

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

我想用自定义字体更改标签的字体,但编译器给了我一个问题:在解开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

1 个解决方案

#1


2  

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

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

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

#1


2  

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

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

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