Swift How to calculate one line text height from its font

I have been searching for a way to do that and find this answer where it has a String extension to calculate the size for the string and a given font. I have modified it to do what I want (get the line height of text written using a font.):

extension UIFont {
    func calculateHeight(text: String, width: CGFloat) -> CGFloat {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let boundingBox = text.boundingRect(with: constraintRect,
                                        options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                        attributes: [NSAttributedStringKey.font: self],
                                        context: nil)
        return boundingBox.height
    }
}

I hope this helps someone looking for it. (may be myself in the future).


UIFont has a property lineHeight:

    if let font = _textView.font {
        let height = font.lineHeight
    }

where font is your font