Skip to content

Instantly share code, notes, and snippets.

@ankushkushwaha
Created June 27, 2015 10:17
Show Gist options
  • Save ankushkushwaha/f865b709463b556ada4e to your computer and use it in GitHub Desktop.
Save ankushkushwaha/f865b709463b556ada4e to your computer and use it in GitHub Desktop.
Calculate Label Height dynamically in iOS
/**
* Calculate height for a fixed weidht label
* @param UILabel for which height to be calculated
**/
-(double)getLabelHeightForLabel:(UILabel *)label{
CGSize constrainedSize = CGSizeMake(label.frame.size.width, 1000);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: label.font, NSFontAttributeName,nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:label.text attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.width > label.frame.size.width) {
requiredHeight = CGRectMake(0,0, label.frame.size.width, requiredHeight.size.height);
}
return requiredHeight.size.height;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment