How to calculate height of a multiline String in Swift

Yesterday I spent like 2 hours trying to find answer to this question. Eventually I had to figure it out on my own using a bunch of Stackoverflow answers, each of which, if used alone, didn’t produce the desired result.

So, here is what I came up with. It works!

 

[SW]

Facebooktwitterredditpinterestlinkedinmail

8 thoughts on “How to calculate height of a multiline String in Swift”

  1. Thank you!

    I leveraged it to :

    func heightNeededForLabel(_ label: UILabel) -> CGFloat {
    let width = label.frame.size.width
    guard let font = label.font else {return 0}
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
    let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
    return boundingBox.height
    }

Leave a Reply

Your email address will not be published. Required fields are marked *