How to resize NSTextView according to its content?

Miraaj picture Miraaj · Apr 16, 2010 · Viewed 9.2k times · Source

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 :(

Answer

hyouuu picture hyouuu · Jan 17, 2019

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
        }
    }
}