Showing posts with label dynamic height. Show all posts
Showing posts with label dynamic height. Show all posts

Sunday, June 17, 2012

Label with dynamic height

The below code creates the dynamic height to fit for the inputed text

-(void)createDynamicHeight
{
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 300, 40)];
label.backgroundColor = [UIColor blackColor];
[self.view addSubview:label];
NSString *text = @"This is label with dynamic height";
label.text = text;
label.lineBreakMode = UILineBreakModeWordWrap;
    
// resize the height to fit the content
CGSize newLabelSize = [text sizeWithFont:label.font 
                       constrainedToSize:label.frame.size
                           lineBreakMode:UILineBreakModeWordWrap];
    
CGRect newFrame = instructions.frame;

if (newLabelSize.height > 40) {
      newFrame.size.height = newLabelSize.height;
} else {
      newFrame.size.height = 40
}
label.frame = newFrame;
label.numberOfLines = 0;

NSLog(@"Label height is %f", label.frame.size.height);
}