Wrong height for font text

2020-02-15 ios swift

I am trying to calculate the height of a block of text using the following function:

extension String {
    func height(forWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constrainedSize = CGSize(width: width, height: .greatestFiniteMagnitude)
        let attributes = [NSAttributedString.Key.font: font]
        let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
        let bounds = (self as NSString).boundingRect(with: constrainedSize, options: options, attributes: attributes, context: nil)
        return ceil(bounds.height)
    }
}

I use it like so:

let height = text.height(forWidth: 325.0, font: UIFont(name: "FuturaPT-Book", size: Styles.Sizes.Text.body)!)

For some reason, this doesn't produce the correct height. It returns 245.0, but the text on screen is actually of a height of 187.0. I've double checked that the text is bound to a width of 325.0 on screen, and it is. So it's not a width mismatch. Why is this? Could it be something wrong with my font file, or is there something wrong in the code?

UPDATE

I just removed .usesFontLeading and now it works fine. Can anyone explain this?

Answers

Related