Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 7 sizeWithAttributes: replacement for sizeWithFont:constrainedToSize

How do you return a multiline text CGSize from the new iOS 7 method sizeWithAttributes?

I would like this to produce the same results as sizeWithFont:constrainedToSize.

NSString *text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu urna quis lacus imperdiet scelerisque a nec neque. Mauris eget feugiat augue, vitae porttitor mi. Curabitur vitae sollicitudin augue. Donec id sapien eros. Proin consequat tellus in vehicula sagittis. Morbi sed felis a nibh hendrerit hendrerit. Lorem ipsum dolor sit."

CGSize textSize = [text sizeWithAttributes:@{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:16.0] }];

This method only produces the height for a single line of text.

like image 598
morcutt Avatar asked Oct 02 '13 19:10

morcutt


2 Answers

well you can try this :

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
CGRect rect = [textToMeasure boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attributes
                                          context:nil];
like image 90
oiledCode Avatar answered Dec 06 '22 11:12

oiledCode


This is how I did it:

    // Get a font to draw it in
UIFont *font = [UIFont boldSystemFontOfSize: 28];

CGRect textRect;
NSDictionary *attributes = @{NSFontAttributeName: font};

// How big is this string when drawn in this font?
textRect.size = [text sizeWithAttributes:attributes];

// Draw the string
[text drawInRect:textRect withAttributes:attributes];
like image 26
Gnawbone Avatar answered Dec 06 '22 13:12

Gnawbone