If I call
If, however, I call this with a font such as Arial
Then scaledFont.pointSize has value 12. I was expecting 17, so I must be doing something wrong. Any suggestion?
The function fontWithNameAndTraits is:
Code Block let font = UIFont.preferredFont(forTextStyle:.body)
Then font.pointSize has value 17If, however, I call this with a font such as Arial
Code Block let font = UIFont.fontWithNameAndTraits(fontName, size: styleAttributes.fontSize ?? 12, bold: styleAttributes.bold ?? false, italic: styleAttributes.italic ?? false) let fontMetrics = UIFontMetrics(forTextStyle: .body) let scaledFont = fontMetrics.scaledFont(for: font)
Then scaledFont.pointSize has value 12. I was expecting 17, so I must be doing something wrong. Any suggestion?
The function fontWithNameAndTraits is:
Code Block class func fontWithNameAndTraits(_ name:String, size:CGFloat, bold:Bool, italic:Bool)->UIFont { let fontRef = UIFont.getFontRefForNameAndTraits(name, size:size, bold:bold, italic:italic) let fontNameKey = CTFontCopyName(fontRef , kCTFontPostScriptNameKey)! as String return UIFont(name: fontNameKey as String, size:CTFontGetSize(fontRef ))! }
Just found that the following code does the trick, it just needs amending to include traits:
Code Block class func preferredCustomFont(for fontFamily: String, andTextStyle textStyle: UIFont.TextStyle) -> UIFont { let systemFontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle) let customFontDescriptor = UIFontDescriptor.init(fontAttributes: [ UIFontDescriptor.AttributeName.family: fontFamily, UIFontDescriptor.AttributeName.size: systemFontDescriptor.pointSize // use the font size of the default dynamic font ]) // return font of new family with same size as the preferred system font return UIFont(descriptor: customFontDescriptor, size: 0) }