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 } } |
![Share on Facebook Facebook](https://successfulcoder.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/48x48/facebook.png)
![Share on Twitter twitter](https://successfulcoder.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/48x48/twitter.png)
![Share on Reddit reddit](https://successfulcoder.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/48x48/reddit.png)
![Pin it with Pinterest pinterest](https://successfulcoder.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/48x48/pinterest.png)
![Share on Linkedin linkedin](https://successfulcoder.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/48x48/linkedin.png)
![Share by email mail](https://successfulcoder.com/wp-content/plugins/social-media-feather/synved-social/image/social/regular/48x48/mail.png)
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