Tarun Seera
Tarun Seera

Reputation: 4412

sizeWithAttributes Returning Wrong Size with New Line Character \n

I am using sizeWithAttributes method of NSString to get dynamic height of NSString.

My String is @"This is address line1 \n This is address line2"

but the methods returning only size for line1 (before the \n character)

Is there any way to include \n in string size?

Upvotes: 4

Views: 1323

Answers (1)

rmaddy
rmaddy

Reputation: 318934

You can't use sizeWithAttributes to calculate the size of multi-line text. Think about it. The size of multi-line text is dependent on how much width it has to be drawn in. sizeWithAttributes doesn't let you specify the allotted width.

You need to use boundingRectWithSize:options:attributes:context:. Specify a size with a desired width and a very large height. The returned value will give you the required size to wrap the text within the specified size.

One example of its use would be:

NSString *addressString = ... // your string to measure
NSDictionary *attributes = @{ NSFontAttributeName : [UIFont fontWithName:kFontName size:kProductFont] };
CGFloat desiredWidth = 300; // adjust accordingly
CGRect neededRect = [addressString
                        boundingRectWithSize:CGSizeMake(desiredWidth, CGFLOAT_MAX)
                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                        attributes:attributes context:nil];
CGFloat neededHeight = neededRect.size.height;

Upvotes: 5

Related Questions