我试图在这里初始化我的自定义字体,但它显示错误。
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/