.usesFontLeading gives a different height when used with boundingRect

I'm using boundingRect to calculate the height of a String, I'm using Ubuntu as my font, and when I supply .usesFontLeading as one of the options alongside .usesLineFragmentOrigin the height is completely different to what I expect.

Here is the code I'm using for reference:

func height(withConstrainedWidth width: CGFloat, font: UIFont, maxLines: CGFloat = 0) -> CGFloat {

        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)

        let boundingBox = self.boundingRect(with: constraintRect, options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: [

            NSAttributedString.Key.font: font

        ], context: nil)

        var size = boundingBox.size

        if maxLines > 0 {

            size.height = min(size.height, CGFloat(maxLines) * font.lineHeight)

        }

        return ceil(size.height)

    }

Firstly, what does .usesFontLeading even do, and why is it that the result I'm getting an unexpected result.

Note: self is String because I've extended the String class.

Replies

AFAIK, it is normal. Without usesLineFragmentOrigin, height is calculated for a single line. So difference may be 40 instead of 20 for instance.

Doc states: To calculate the bounding rectangle, this method uses the baseline origin by default, so it behaves as a single line. To render the string in multiple lines, specify usesLineFragmentOrigin in options.

  • Hey, I want to know what .usesFontLeading does, and will it cause any problems if I don't add that as an options?

    Right now, If I remove .usesFontLeading, everything works the way I expect it to, the height calculations are accurate, the moment I add the option in, everything just gets weird, inaccurate heights, etc. My concern is, since I'm using a custom font, will it cause any issues in production if I don't add the option?

Add a Comment