Try following sample font extension with Swift 4. (It needs some improvement for all types of font weights)
extension UIFont {
func getFontWeight() -> UIFont.Weight {
let fontAttributeKey = UIFontDescriptor.AttributeName.init(rawValue: "NSCTFontUIUsageAttribute")
if let fontWeight = self.fontDescriptor.fontAttributes[fontAttributeKey] as? String {
switch fontWeight {
case "CTFontBoldUsage":
return UIFont.Weight.bold
case "CTFontBlackUsage":
return UIFont.Weight.black
case "CTFontHeavyUsage":
return UIFont.Weight.heavy
case "CTFontUltraLightUsage":
return UIFont.Weight.ultraLight
case "CTFontThinUsage":
return UIFont.Weight.thin
case "CTFontLightUsage":
return UIFont.Weight.light
case "CTFontMediumUsage":
return UIFont.Weight.medium
case "CTFontDemiUsage":
return UIFont.Weight.semibold
case "CTFontRegularUsage":
return UIFont.Weight.regular
default:
return UIFont.Weight.regular
}
}
return UIFont.Weight.regular
}
Try with label:
let label = UILabel()
var fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold)
fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.black)
fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.heavy)
fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.ultraLight)
fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.thin)
fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.light)
fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
fontWeight = label.font.getFontWeight()
print("fontWeight - \(fontWeight)")
Here is Apple document for list of Font Weights
The value of this weight is an NSNumber object. The valid value range is from -1.0 to 1.0. The value of 0.0 corresponds to the regular or medium font weight. You can also use a font weight constant to specify a particular weight.
label.font.UIFontWeight
– Trypanosomiasis