noname noname - 3 years ago 318
Swift Question

Get font attributes in swift 4

I've migrated project from swift 3 to swift 4 and cannot find a info how to get a font attribute from a

UIFontDescriptor
. Here is the code which works perfect in swift 3 :

@objc convenience init(myCoder aDecoder: NSCoder) {
if let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor {
if let fontAttribute = fontDescriptor.fontAttributes["NSCTFontUIUsageAttribute"] as? String {
var fontName = ""
switch fontAttribute {
case "CTFontRegularUsage":
fontName = Roboto.regular.rawValue
case "CTFontEmphasizedUsage", "CTFontBoldUsage":
fontName = Roboto.bold.rawValue
default:
fontName = Roboto.regular.rawValue
}
self.init(name: fontName, size: fontDescriptor.pointSize)!
}
else {
self.init(myCoder: aDecoder)
}
}
else {
self.init(myCoder: aDecoder)
}
}


But In swift 4 the line :

if let fontAttribute = fontDescriptor.fontAttributes["NSCTFontUIUsageAttribute"] as? String


has an error :
Ambiguous reference to member 'subscript'
.
Any ideas how can I change it ?

Thanks!

Answer Source

It looks like you're trying to treat your custom font as a dynamic type font. The supported way to do that in iOS 11 is to use UIFontMetrics.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download