0

I have found several good answers about how to calculate the height of UILabel with a given text and the UIFont:

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

However, I want to go a little bit further and calculate the height with a given text, font and number of lines. Is that even possible? So, if the height is supposed to be in 2 lines, I would like the height for 2 lines.

Thank you.

Reimond Hill
  • 4,278
  • 40
  • 52
  • Is this what you were looking for? https://stackoverflow.com/questions/7174007/how-to-calculate-uilabel-height-dynamically – Rob C Mar 03 '20 at 16:45

1 Answers1

0

In Swift 5:

Rob pointed me in the right direction and I saw that the number of lines can be achieved by using the UIFont.lineHeight.

Solution for getting the right height with a given text, width and max number of lines.

func height(width: CGFloat, font: UIFont, maxLines: CGFloat = 0) -> CGFloat {
    //Calculating height
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
    let boundingBox = self.boundingRect(with: constraintRect,
                                        options: [.usesLineFragmentOrigin, .usesFontLeading],
                                        attributes: [NSAttributedStringKey.font: font], context: nil)

    let height = ceil(boundingBox.height)
    if maxLines > 0 {
        let lines = height / font.lineHeight

        if lines >= maxLines {
            return (boundingBox.height / lines) * maxLines
        }

    }

    return height
}
Reimond Hill
  • 4,278
  • 40
  • 52