すでに述べたように、NSTextField と UITextField は非常に異なるオブジェクトです (その名前が示唆するものとは反対です)。具体的には、NSTextField の場合、NSLayoutManager を含む洗練されたソリューションを使用できます。NSLayoutManager オブジェクトは、NSTextStorage オブジェクトに保持されている文字のレイアウトと表示を調整します。Unicode 文字コードをグリフにマップし、一連の NSTextContainer オブジェクトにグリフを設定し、一連の NSTextView オブジェクトに表示します。
必要なのは、NSLayoutManager、NSTextContainer、および NSTextStorage を作成することだけです。これらは、同様の方法ですべてまとめてラップします。
.-----------------------.
| NSTextStorage |
| .-----------------. |
| | NSLayoutManager | |
| '-----------------' |
| | NSTextStorage | |
| '-----------------' |
| |
'-----------------------'
そうは言っても、layoutManager メソッドを使用してusedRectForTextContainer:
、目的のテキストを含む正しいサイズを見積もることができます。
以下はあなたの問題に対してうまくいくはずです:
- (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;
}
このトピックに関する包括的な Apple ドキュメントがあります。
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TextLayout/Tasks/StringHeight.html#//apple_ref/doc/uid/20001809-CJGBBIBB
また、何人かのベテランが Apple メーリング リストでこの問題を分析しています。
http://lists.apple.com/archives/cocoa-dev/2006/Jan/msg01874.html