【问题标题】:swift 4: cannot subscript a value of type '[UIFontDesciptor.AttributeName : Any]' with an index of type 'String'swift 4:不能用“String”类型的索引为“[UIFontDeciptor.AttributeName:Any]”类型的值下标
【发布时间】:2018-04-06 06:05:09
【问题描述】:

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

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 一起运行。请帮我。提前致谢。

【问题讨论】:

    标签: ios swift4 uifont custom-font


    【解决方案1】:

    字体属性标识符的类型已由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 {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      相关资源
      最近更新 更多