View Full Version : How do I create a NSTextField that displays entire string, no matter the font?

Jan 21, 2009, 06:17 AM
Hi all!

I want to create an NSTextField as big as the NSString that should be displayed in it.

I tried the following code:

NSString *myString = @"blabla blabla";
NSUInteger len =[myString length];

NSFont* mySystemFont = [NSFont systemFontOfSize:[NSFont systemFontSize]];
NSRect mySystemFontRect = [mySystemFont boundingRectForFont];

NSRect textFieldRect = NSMakeRect(0,0,len*mySystemFontRect.size.width,20);

But the NSTextField that I created next using this textFieldRect, is far too big (width is too big) for my string!

What I actually want to ensure is that, no matter what the font is, the NSTextField will display the entire string.
Anyone has any idea what should I try next?


Jan 21, 2009, 10:54 AM
If you're targetting OSX 10.4 and above, you could take a look at:

NSString's instance method: boundingRectWithSize: options: attributes:

Take a look here (http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/ApplicationKit/Classes/NSString_AppKitAdditions/Reference/Reference.html#//apple_ref/occ/instm/NSString/boundingRectWithSize:options:attributes:)