如何根据内容调整NSTextView的大小?

时间:2010-04-16 16:26:57

标签: cocoa nstextview

我正在尝试在NSTextView中设置属性字符串。我想根据其内容增加其高度,最初将其设置为某个默认值。

所以我试过这个方法:

我在NSTextView中设置内容。当我们在NSTextView中设置一些内容时,它的大小会自动增加。所以我将其超级视图的高度NSScrollView增加到它的高度,但是NSScrollView没有完全调整大小,它在右边显示了滚动条。

float xCoordinate = 15.0;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, 10.0)];

[[xContentView textStorage] setAttributedString:xContents];

float xContentViewScrollerHeight = [xfContentView frame].size.height + 2;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, xContentViewScrollerHeight)]; 

任何人都可以建议我解决此问题的方法或方法。通过谷歌搜索,我发现在UITextView中有contentSize方法可以获得其内容的大小,我试图在NSTextView中找到类似的方法,但无法取得任何成功:(

4 个答案:

答案 0 :(得分:17)

答案 1 :(得分:6)

NSTextView *textView = [[NSTextView alloc] init];
textView.font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
textView.string = @"Lorem ipsum";

[textView.layoutManager ensureLayoutForTextContainer:textView.textContainer];

textView.frame = [textView.layoutManager usedRectForTextContainer:textView.textContainer];

答案 2 :(得分:1)

+ (float)heightForString:(NSString *)myString font:(NSFont *)myFont andWidth:(float)myWidth andPadding:(float)padding {
     NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:myString];
     NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(myWidth, FLT_MAX)];
     NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
     [layoutManager addTextContainer:textContainer];
     [textStorage addLayoutManager:layoutManager];
     [textStorage addAttribute:NSFontAttributeName value:myFont
                    range:NSMakeRange(0, textStorage.length)];
     textContainer.lineFragmentPadding = padding;

     (void) [layoutManager glyphRangeForTextContainer:textContainer];
     return [layoutManager usedRectForTextContainer:textContainer].size.height;
}

我使用此引用完成了该功能:Documentation

示例:

float width = textView.frame.size.width - 2 * textView.textContainerInset.width;
float proposedHeight = [Utils heightForString:textView.string font:textView.font andWidth:width
                                   andPadding:textView.textContainer.lineFragmentPadding];

答案 3 :(得分:1)

基于@Peter Hosey的回答,这是Swift 4.2中NSTextView的扩展:

extension NSTextView {

    var contentSize: CGSize {
        get {
            guard let layoutManager = layoutManager, let textContainer = textContainer else {
                print("textView no layoutManager or textContainer")
                return .zero
            }

            layoutManager.ensureLayout(for: textContainer)
            return layoutManager.usedRect(for: textContainer).size
        }
    }
}