I have a Label which takes dynamicaly some data from database. These data are strings which can sometimes be 3-4-5 rows etc. So this labe is inside a UIView.
first calculate the size of label with the text it contains, using this function
func calculateSizeOfLabel(text:String,labelWidth:CGFloat,labelFont:UIFont)->CGSize{
let constrainedSize = CGSizeMake(labelWidth , 9999)
var attributesDictionary:[String:AnyObject] = [:]
attributesDictionary = [NSFontAttributeName:labelFont] as [String:AnyObject]
let string:NSMutableAttributedString = NSMutableAttributedString(string:text, attributes:attributesDictionary)
var boundingRect = string.boundingRectWithSize(constrainedSize, options:.UsesLineFragmentOrigin, context:nil)
if (boundingRect.size.width > labelWidth) {
boundingRect = CGRectMake(0,0, labelWidth, boundingRect.size.height);
}
return boundingRect.size
}
and then apply the height of returned size to the UIView like this
let labelText = description.text
let labelWidth = description.bounds.width
let labelFont = description.font
let calculatedHeight = calculateSizeOfLabel(labelText,labelWidth:labelWidth,labelFont:labelFont).height
DescView.frame = CGRectMake(DescView.frame.origin.x, DescView.frame.origin.y, DescView.bounds.width,calculatedHeight)