Dynamic type & custom font

If I call
Code Block
let font = UIFont.preferredFont(forTextStyle:.body)
Then font.pointSize has value 17

If, 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 ))!
    }


Answered by Easiwriter in 671027022
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)
    }


Accepted Answer
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)
    }


Dynamic type & custom font
 
 
Q