Saturday, November 22, 2008

sizing UILabel accordingly to the height of the string

In my app I needed to resize the UILabel size dynamically in runtime as the text would not be determined during compilation time. Luckily this can be done by using the sizeWithFont method of NSString class.
  1. Call sizeWithFont of the text.
  2. Get back a CGSize struct and you can now init your UILabel with the struct.
UIFont *font = [UIFont systemFontOfSize:14];

CGSize textSize = [ myText sizeWithFont: font constrainedToSize: CGSizeMake(lineWidth, lineHeight*1000.0f) lineBreakMode: UILineBreakModeTailTruncation ];

UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(10,10,textSize.width,textSize.height)];

This took me awhile to find out..hope it helps you. Happy coding.

No comments: