我正在尋找一個測量字符串高度的程序,並且我發現這個問題在另一個堆棧溢出問題上。它適用於我的NSTableViewColumns有Word換行作爲換行符 我的問題是,如果我將換行符更改爲字符換行,如何更新此代碼?在Cocoa中測量字符串高度
- (NSSize)sizeForWidth:(float)width
height:(float)height {
NSSize answer = NSZeroSize ;
gNSStringGeometricsTypesetterBehavior = NSTypesetterBehavior_10_2_WithCompatibility;
if ([self length] > 0) {
// Checking for empty string is necessary since Layout Manager will give the nominal
// height of one line if length is 0. Our API specifies 0.0 for an empty string.
NSSize size = NSMakeSize(width, height) ;
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:size] ;
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:self] ;
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init] ;
[layoutManager addTextContainer:textContainer] ;
[textStorage addLayoutManager:layoutManager] ;
[layoutManager setHyphenationFactor:0.0] ;
if (gNSStringGeometricsTypesetterBehavior != NSTypesetterLatestBehavior) {
[layoutManager setTypesetterBehavior:gNSStringGeometricsTypesetterBehavior] ;
}
// NSLayoutManager is lazy, so we need the following kludge to force layout:
[layoutManager glyphRangeForTextContainer:textContainer] ;
answer = [layoutManager usedRectForTextContainer:textContainer].size ;
[textStorage release] ;
[textContainer release] ;
[layoutManager release] ;
// In case we changed it above, set typesetterBehavior back
// to the default value.
gNSStringGeometricsTypesetterBehavior = NSTypesetterLatestBehavior ;
}
return answer ;
}
感謝您的回覆,即使使用段落樣式,boundingRectWithSize也會返回單行大小的矩形,可能會出現什麼錯誤? –
你在選項中包含了'NSStringDrawingUsesLineFragmentOrigin'標誌嗎? – trss
謝謝! NSStringDrawingUsesLineFragmentOrigin正在爲我工作! –