Iphone: sizeWithFont method does not identify '\ n' from string

I am using the code below to calculate the label size for a string.

    NSString * str = @"It \n that \n don't \n";
    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Verdana" size:12.5] forWidth:300  
     lineBreakMode:UILineBreakModeWordWrap];
    NSLog(@"Height : %f   Width : %f ",size.height,size.width);

But id does not consider \ n characters from a string to change the string. When I show this line on a shortcut and set its numberOfLines property to 4 or 5, the label considers \ n and moves on to the next line. How to calculate height for lable given \ n from string. Please help me.

Thank!

+5
source share
1 answer

Try the following:

NSString * str = @"It \n that \n don't \n";
CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Verdana" size:12.5] constrainedToSize:CGSizeMake(300.0f, 999999.0f)];
NSLog(@"Height : %f   Width : %f ",size.height,size.width);

This will give me Height : 48.000000 Width : 40.000000, but be sure to set the number of lines in the label 0.

+5
source

All Articles