1

我正在寻找一个高度测量字符串程序,我在另一个堆栈溢出问题中找到了这个程序。它非常适用于我的 NSTableViewColumns,它具有 Word Wrap 作为换行符我的问题是,如果我将换行符更改为字符换行,我该如何更新此代码?

- (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 ;
}
4

1 回答 1

2

这感觉就像你在重新发明[NSAttributedString boundingRectWithSize:options:](或只是size)。我在您的实施中遗漏了什么吗?NSLayoutManager用于处理快速变化的字符串的布局(例如在文本视图中)。大多数时候都是矫枉过正。您故意绕过其优化(在您的行中指出这NSLayoutManager是懒惰的,您的意思是优化:D)

在任何一种情况下,要更改包装行为,您都需要修改NSAttributedString自身。换行是段落样式的一部分。像这样的东西(未经测试;可能无法编译):

// Lazy here. I'm assuming the entire string has the same style
NSMutableParagraphStyle *style = [[self attribute:NSParagraphStyleAttributeName atIndex:0 effectiveRange:NULL] mutableCopy]; 
[style setLineBreakMode:NSLineBreakByCharWrapping];
NSAttributedString *charWrappedString = [self mutableCopy];
[charWrappedString setAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, [self length]];

NSRect boundingRect = [self boundingRectWithSize:NSMakeSize(width, height) options:0];
NSSize size = boundRect.size;

[style release];
[charWrappedString release];

return size;

样式有点棘手,因为它们包含几个东西,但你必须将它们全部设置在一起。因此,如果属性字符串中有不同的样式,则必须遍历字符串,处理每个effectiveRange. (您需要阅读文档以了解 和 之间的权衡attributesAtIndex:effectiveRange:attributesAtIndex:longestEffectiveRange:inRange:

于 2012-01-21T01:51:35.793 回答