ios - 将 CATextLayer 字体转换为 UIFont

标签 ios swift cocoa

CATextLayer.font 属性是一个不透明的 CFTypeRef。有没有办法将该引用转换为 UIFont?我不介意它是否返回可选的 UIFont。

最佳答案

我刚刚编写了以下应该处理的扩展:CTFontCGFont、字符串名称或 UIFont:

extension CATextLayer {
    public var typeFace:UIFont? {
        let name:String
        switch font {
        case let ctFont as CTFont :
            // If you assign a UIFont to CATextLayer.font
            // it is implicitly converted to CTFont,
            // so this case will be called.
            guard let _name = CTFontCopyName(ctFont, kCTFontPostScriptNameKey) else {
                return nil
            }
            name = _name as NSString as String
        case let cgFont as CGFont :
            guard let _name = cgFont.postScriptName else {
                return nil
            }
            name = _name as NSString as String
        case let string as NSString :
            name = string as String
        case let string as String :
            name = string
        default:
            return nil
        }
        return UIFont(name:name, size:fontSize)
    }
}

附带说明一下,我发现文档中的这条评论不准确:

In iOS, you cannot assign a UIFont object to this property.

根据我的测试,我能够在 CATextLayer.font 上设置一个 UIFont,它似乎工作正常。


编辑

事实证明,当您将 UIFont 分配给 CATextLayer.font 时,它会在幕后转换为 CTFont,因此为了返回 UIFont 有必要将 CTFont 转换为 UIFont(我的代码就是这样做的)。简单地转换为 UIFont 是行不通的。

关于ios - 将 CATextLayer 字体转换为 UIFont,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47922763/

相关文章:

cocoa - 观察值ForKeyPath :ofObject:change:context: doesn't work properly with arrays

ios - 类型 'GIDSignIn' 的值没有成员 'presentingViewController'

swift - 以编程方式将列添加到 NSTableView

swift - 如果在 set double 中没有值返回到带有 guard let 语句的设定数字

objective-c - 检索用于在应用程序中打开文档的 Spotlight 查询

macos - 当我不需要多文档支持时使用 NSDocument?

ios - 无法设置 View Controller 的标题

ios - 使用 Realm 存储数据,添加对象清除列表中的对象

ios - 使用 NSKeyedUnarchiver 加载数据时应用程序崩溃

ios - 当用户在 UITextView 中选择特定单词时