I am trying to calculate the height of a UILabel based on different String lengths.
func calculateContentHeight() -> CGFloat{
var maxLabelSize: CGSize = CGSizeMake(frame.size.width - 48, CGFloat(9999))
var contentNSString = contentText as NSString
var expectedLabelSize = contentNSString.boundingRectWithSize(maxLabelSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(16.0)], context: nil)
print("\(expectedLabelSize)")
return expectedLabelSize.size.height
}
Above is the current function I use to determine the height but it is not working. I would greatly appreciate any help I can get. I would perfer the answer in Swift and not Objective C.
This is my answer in Swift 4.1 and Xcode 9.4.1
Now you call this function
Use an extension on
String
Swift 3
and also on
NSAttributedString
(which is very useful at times)Swift 4
Just change the value for
attributes
in theextension String
methodsfrom
to
For multiline text this answer is not working correctly. You can build a different String extension by using UILabel
The UILabel gets a fixed width and the .numberOfLines is set to 0. By adding the text and calling .sizeToFit() it automatically adjusts to the correct height.
Code is written in Swift 3