20

我正在尝试在 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

3 回答 3

9

根据@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
        }
    }
}
于 2019-01-17T02:29:38.237 回答
8
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];
于 2017-04-03T11:03:10.860 回答
3
+ (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;
}

我使用这个参考做了这个功能:文档

例子:

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];
于 2017-07-07T11:00:33.187 回答