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!
1 2 3 4 5 6 7 8 |
import UIKit 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 } } |
This was awesome and helped solved a problem I’ve had for a week or so. Thanks!
Thanks much.. this helped me in a time of need..
how to use it…?
Update for Swift 4
NSFontAttributeName = NSAttributedStringKey.font
Thanks! I updated the post.
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
}
Awesome, It’s saves my lots of Time 🙂
Awesome work, just what I needed