ios - swift 4 : cannot subscript a value of type '[UIFontDesciptor.AttributeName : Any]' with an index of type 'String'

标签 ios swift4 uifont custom-font

我试图在这里初始化我的自定义字体,但它显示错误。

extension UIFont {
@objc convenience init(myCoder aDecoder: NSCoder) {
    if let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor {
        if let fontAttribute = fontDescriptor.fontAttributes["NSCTFontUIUsageAttribute"] as? String { // HERE SHOWING THE ERROR
            var fontName = ""
            switch fontAttribute {
            case "CTFontRegularUsage":
                fontName = appFontName
            case "CTFontEmphasizedUsage", "CTFontBoldUsage":
                fontName = appFontBoldName
            case "CTFontObliqueUsage":
                fontName = appFontItalicName
            default:
                fontName = appFontName
            }
            self.init(name: fontName, size: fontDescriptor.pointSize)!
        }
        else {
            self.init(myCoder: aDecoder)
        }
    }
    else {
        self.init(myCoder: aDecoder)
    }
}
...
}

这非常适用于 swift-3.2。但它没有与 swift-4.0 一起运行。请帮我。提前致谢。

最佳答案

字体属性标识符的类型已从 String 更改为 UIFontDescriptor.AttributeName

好处是你可以声明一个扩展

extension UIFontDescriptor.AttributeName {
    static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}

然后就可以写了

if let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String {

或不带扩展名

if let fontAttribute = fontDescriptor.fontAttributes[UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")] as? String {

关于ios - swift 4 : cannot subscript a value of type '[UIFontDesciptor.AttributeName : Any]' with an index of type 'String' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927510/

相关文章:

ios - iOS 8.2 之前的 UIFont.systemFontOfSize 权重

objective-c - UIFont 的磅值到底是多少?

ios - Interface Builder 中具有空 UIStackView 的 UIScrollView 的约束错误

ios - 使用 dismissViewControllerAnimated 时如何重新加载 View

swift - 如何修复 "could not find ' init(域:code:userInfo: )' in parent class" while archiving?

Swift 4 'substring(from:)' 已弃用 : Please use String slicing subscript with a 'partial range from' operator

ios - Xcode 6 中的自定义字体

html - 无法使用 loadHTMLString :baseURL in iOS? 在 UIWebView 中加载 html 字符串

ios - 从 PDFDocument iOS 获取页面大小

ios - 如何快速从一系列键值对(元组)创建两个字符串数组