0

I have a NSString with any number of characters. Now wand to draw this String into a rect. The rect needs to be for example 250 pixels wide.

I wand to know how to get the height of this text with a specific font and size.

Jonas Ester
  • 83
  • 2
  • 8

2 Answers2

-1

From the NSString UIKit Additions (https://developer.apple.com/library/ios/documentation/uikit/reference/NSString_UIKit_Additions/DeprecationAppendix/AppendixADeprecatedAPI.html#//apple_ref/occ/instm/NSString/sizeWithFont:constrainedToSize:)

use sizeWithFont:constrainedToSize:lineBreakMode:

Use it in a way that you use constraints with a width of 250 in your case and some very high amount in height (let's say 10000). Then it returns the actual width (which may be slightly smaller than 250) and the height needed.

But be aware that it was deprecated recently. You can use boundingRectWithSize:options:attributes:context: From iOS 7 onwards. Usually a deprecated method is around for a while but you cannot rely on that. So if you want your app to run in iOS 6 or even older then you would probably go with the deprecated method for a while or you could check the OS and either use the old or the new method for going forward.

Apologies if you are on OS-X and not iOS. In that case my answer would not be helpful at all. You did not tag the OS.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71
-1

You can get the height and width using the 'sizeWithFont:' method as shown below:

UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];

// Get the width of a string ...
CGSize size = [@"Some string here!" sizeWithFont:myFont];

CGSize is a C structure, so you can access the height and width as follows:

  // Print height and width
  NSLog(@"h: %f \t w:%f", size.height, size.width);
John Muchow
  • 4,798
  • 8
  • 40
  • 40
  • `sizeWithFont` is deprecated in iOS 7. http://stackoverflow.com/questions/18897896/replacement-for-deprecated-sizewithfont-in-ios-7 – swilliams May 21 '14 at 16:50