Question

From https://developer.apple.com/library/ios/documentation/uikit/reference/NSString_UIKit_Additions/Reference/Reference.html#//apple_ref/occ/instm/NSString/sizeWithAttributes::

UITextAttributeFont
Key to the font in a text attributes dictionary.
The corresponding value is an instance of UIFont.
Use a font with size 0.0 to get the default font size for the current context.
Available in iOS 5.0 and later.
Deprecated in iOS 7.0.
Declared in UIStringDrawing.h.

I am trying to get the width (height also desired) for a particular one-line string of text, and this is what I have now, "..." being what I need to appropriately initialize the font. The method is incomplete (it doesn't return a value), but I would like a non-deprecated way to specify a font's information and get back how many pixels wide the string would be if drawn.

-(float)getLength:(NSString *)text
{
    CGSize size = [text sizeWithAttributes:[[NSDictionary alloc] initWithObjectsAndKeys:...];
}

Have the semantics changed from "Specify font details when you are making the final call" to "Specify font details once, and they will remain in effect until you change them to something else"?

Thanks,

Was it helpful?

Solution

I was looking at an issue really close to your problem for my own work just a few days ago.

The call you're looking for (which will solve your ultimate problem) is "boundingRectWithSize: options: attributes: context:", where you pass in the UIFont you loaded (from your TTF file) as one of the attributes.

Even better, use a NSAttributedString or NSMutableAttributedString (which also has a "boundingRectWithSize: options: context:" method, because then you can calculate your text width and height with a mix of fonts and font styles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top