2

The following code allows to create a font with different weights.

func makeFont(weight: CGFloat, size: CGFloat) -> UIFont {
    var attributesDict = [String: Any]()
    attributesDict["Weight"] = weight
    /* Rubik-Light - is a variable font */
    let fontDescriptor = UIFontDescriptor(
        fontAttributes: [
            UIFontDescriptor.AttributeName.name : "Rubik-Light",
            kCTFontVariationAttribute as UIFontDescriptor.AttributeName : attributesDict
        ]
    )
    return UIFont(descriptor: fontDescriptor, size: size)
}

It works fine on ios 13 and below, but doesn't work on iOS 14. Is there any solution?

zeytin
  • 5,545
  • 4
  • 14
  • 38
RPlay
  • 301
  • 2
  • 10

1 Answers1

6

Solved. iOS 14 expects attribute ID instead of its name ("Weight").

So, attributeDict should look like this:

var attributesDict = [NSNumber: Any]()
attributesDict[NSNumber(value: 2003265652)] = weight

Attribute ID can be obtained as follows:

let variationAxes = (CTFontCopyVariationAxes(ctFont)! as Array)
RPlay
  • 301
  • 2
  • 10
  • 1
    Thank you for posting your solution. Btw, this number is just the four ascii characters of "wght" (the registered OpenType axis) interpreted as UInt32 (0x77676874) – ernesto Oct 21 '21 at 14:52