Dynamic width and height for UILabel in iPhone

Having dynamic text to be displayed in application is a basic requirement.


When you want to display the text, we can calculate the size of the dynamic text using the below code.


  CGSize dynamicSize = [ sizeWithFont:[UIFont boldSystemFontOfSize:14.0] constrainedToSize:CGSizeMake(320, 999) lineBreakMode:UILineBreakModeWordWrap];


The font, constrainedToSize and lineBreakMode should be updated based on the requirement.


Now, dynamic height value can be derived like,


  NSLog(@"Dynamic Text Width: %f \nHeight: %f", dynamicSize.width, dynamicSize.height);


And, to update the UILabel, use the dynamicSize.height value,


  UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,dynamicSize.width, dynamicSize.height)];


And, ONE MORE THING,


Don't forget to set the numberOfLines property of UILabel to 0.

Comments

Popular posts from this blog

Integrating ZXing QR Code reader in iPhone / iOS applications

Multiple line of text in UIPickerView

Connect Samsung devices to Kies on Mac