As already said, NSTextField and UITextField are very different objects (contrary to what their name suggests). Specifically, for NSTextField you could use an elegant solution involving the NSLayoutManager. An NSLayoutManager object coordinates the layout and display of characters held in an NSTextStorage object. It maps Unicode character codes to glyphs, sets the glyphs in a series of NSTextContainer objects, and displays them in a series of NSTextView objects.
All that you need is to create a NSLayoutManager an NSTextContainer and an NSTextStorage. They wrap all together in a similar fashion:
.-----------------------.
| NSTextStorage |
| .-----------------. |
| | NSLayoutManager | |
| '-----------------' |
| | NSTextStorage | |
| '-----------------' |
| |
'-----------------------'
That said, you can use the layoutManager method usedRectForTextContainer:
to estimate the correct size containing your desired text.
The following should work for your problem:
- (float)heightForStringDrawing:(NSString *)aString withFont:(NSFont *)aFont andWitdh:(float)myWidth
{
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:aString];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(myWidth,CGFLOAT_MAX)];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[layoutManager setTypesetterBehavior:NSTypesetterBehavior_10_2_WithCompatibility];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[textStorage addAttribute:NSFontAttributeName value:aFont
range:NSMakeRange(0,[textStorage length])];
[textContainer setLineFragmentPadding:0.0];
NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer];
[layoutManager drawGlyphsForGlyphRange: glyphRange atPoint:NSMakePoint(0, 0)];
return [layoutManager usedRectForTextContainer:textContainer].size.height;
}
There's an exhaustive Apple document about this topic:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TextLayout/Tasks/StringHeight.html#//apple_ref/doc/uid/20001809-CJBGBIBB
Also, some veterans have dissected the problem on Apple Mailing List some times ago:
http://lists.apple.com/archives/cocoa-dev/2006/Jan/msg01874.html