Tuesday, January 24, 2012

Calculate the height of long text (dynamic height of label, cell, textview)

If you want the dynamic height for tableviewCell, label, textview, you have to calculate the height of the long text within the desired width, either of following method can be used.



- (CGSize)sizeWithFont:(UIFont *)font
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode




The below code can obtain the height.

CGSize boundSize = CGSizeMake(desiredWidth, CGFLOAT_MAX);
CGSize myTextSize = [myText sizeWithFont:myFont constrainedToSize:boundSize lineBreakMode:UILineBreakModeWordWrap];
CGFloat myTextHeight = myTextSize.height;
Remark:

Use CGFLOAT_MAX (or a big number) for the height value in CGSizeMake method.

No comments:

Post a Comment