Tracking the Size of a Text View

You can set an NSTextContainer object to track the size of its NSTextView object and adjust its own size to match whenever the text view size changes. The setHeightTracksTextView: and setWidthTracksTextView: methods allow you to control this tracking for either dimension.

When a text container adjusts its size to match that of its text view, it takes into account the inset specified by the text view so the bounding rectangle is inset from every edge possible. In other words, a text container that tracks the size of its text view is always smaller than the text view in a given dimension by twice the inset. Suppose a text container is set to track width and its text view gives it an inset of (10,10). Now, if the text view’s width is changed to 138, the text container’s top-left corner is set to lie at (10,10) and its width is set to 118, so its right edge is 10 points from the text view’s right edge. Its height remains the same.

Whether it tracks the size of its text view or not, a text container doesn’t grow or shrink as text is added or deleted; instead, the NSLayoutManager object resizes the text view based on the portion of the text container actually filled with text. To allow an text view to be resized in this manner, use setVerticallyResizable: or setHorizontallyResizable: methods (which are inherited from NSText) as needed, set the text container not to track the size of its text view, and set the text container’s size in the appropriate dimension large enough to accommodate a great amount of text—for example, 10,000,000 points (this incurs no cost whatever in processing or storage).

Note that a text view can be resized based on its text container, and a text container can resize itself based on its text view. If you set both objects up to resize automatically in the same dimension, your application can get trapped in an infinite loop. When text is added to the text container, the text view is resized to fit the area actually used for text; this causes the text container to resize itself and relay its text, which causes the text view to resize itself again, and so on ad infinitum. Each type of size tracking has its proper uses; be sure to use only one for either dimension.