2014-01-27 17 views
1


我嘗試使用下面的代碼查找特定字符串的大小:多串有時錯誤的大小

NSAttributedString *attributedString = ...// Actually system font, 13 pt. 
NSSize size = ...// Actually more than string size 
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:size]; 
[textContainer setLineFragmentPadding:0.0]; 

NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; 
[layoutManager setTypesetterBehavior:NSTypesetterBehavior_10_2_WithCompatibility]; // Setting up different typeSetterBehavior would not fixes the size issue 
[layoutManager addTextContainer:textContainer]; 

NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString]; 
[textStorage addLayoutManager:layoutManager]; 

// Layout manager performs layout lazily, force it to lay out the text 
[layoutManager glyphRangeForTextContainer:textContainer]; 

NSSize textSize = [layoutManager usedRectForTextContainer:textContainer].size; 

而在這一點上,textSize對於一些字符串!少於字符串需要。例如,對於「看起來不像字符串值」。返回大小的字符串只能繪製「看起來不像字符串」,但對於@「看起來不像字符串值,這是一個數字。」字符串都可以。

[attributedString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin].size 

NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer]; 
NSSize textSize = [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer].size; 

任何人都可以解釋我爲什麼一些字符串我收到錯誤的大小:當我收到字符串大小

Wrong size Normal size

所有同樣的情況?
謝謝。

回答

4

我猜你在創建顯示文本的視圖時,忽略了NSTextFieldNSTextView兩個文本都有自己的文本框架。

例如,如果您使用的是textView,請將textContainerInset設置爲NSZeroSize並查看該效果是否更好。

+0

是的,謝謝!該標籤將其內容略微插入。 – Lexandr