'NSString.boundingRect fails with "[NSNull renderingMode]: unrecognized selector sent to instance" when specifying font

I'm trying to make a collection view where the cells just consist of a label, and I want the width of each cell to match the width of the text. In order to find the width of each string with a certain font (so I can return that size with CollectionView.sizeForItemAt), I call NSString.boundingRect. However, whenever I specify a font in the attributes argument, my project crashes with a 'NSInvalidArgumentException', reason: '-[NSNull renderingMode]: unrecognized selector sent to instance error.

Here's how I call boundingRect:

let size = CGSize(width: 200, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let attributes = [NSAttributedString.Key.font: UIFont(name: "SF Pro Text", size: 14)]
let size = NSString(string: "test").boundingRect(with: size, options: options, attributes: attributes, context: nil)


Solution 1:[1]

There is a possibility that you will not have the font specified, so I would change code to be sure:

let size = CGSize(width: 200, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let font = UIFont(name: "SF Pro Text", size: 14) ?? UIFont.systemFont(ofSize: 14)
let attributes = [NSAttributedString.Key.font: font]
let size1 = NSString(string: "test").boundingRect(with: size, options: options, attributes: attributes, context: nil)

If you want to see a list of all possible fonts, use:

let familyNames = UIFont.familyNames
for name in familyNames {
    UIFont.fontNames(forFamilyName: name).forEach { print($0) }
}

Solution 2:[2]

This error occurs when the specified font is not found in your project. Check if there is a recent change in your font files.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikola Ristic
Solution 2 Harman