Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize NSTextView according to its content?

Tags:

I am trying to set an attributed string within NSTextView. I want to increase its height based on its content, initially it is set to some default value.

So I tried this method:

I set content in NSTextView. When we set some content in NSTextView its size automatically increases. So I increased height of its super view that is NSScrollView to its height, but NSScrollView is not getting completely resized, it is showing scroller on right.

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)]; 

Can anyone suggest me some way or method to resolve this issue. By doing google search I found that in UITextView there is contentSize method which can get size of its content, I tried to find similar method in NSTextView but could not get any success :(

like image 811
Miraaj Avatar asked Apr 16 '10 16:04

Miraaj


2 Answers

Based on @Peter Hosey's answer, here is an extension to NSTextView in Swift 4.2:

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
        }
    }
}
like image 193
hyouuu Avatar answered Oct 28 '22 10:10

hyouuu


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];
like image 39
Nick Dowell Avatar answered Oct 28 '22 10:10

Nick Dowell