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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With