So, I needed to autoresize NSTextFields in XRay II (vertically only). Sort of a poor man’s WebView. This had to “just work” on certain NSTextFields used by third-party plugins, though, without any extra code or subclassing by the plugin writer.

There are two problems there. One is finding out the actual optimum vertical size, while editing and while not, for any type of border or bezel. Here’s the code I finally worked out, with the kind help of Daniel Jalkut:

- (NSSize)minSizeForContent {
   NSRect frame = [self frame];
   NSRect newf = frame;
   NSTextView* editor = nil;
   if ((editor = (NSTextView*)[self currentEditor])) {
      newf = [[editor layoutManager] usedRectForTextContainer:[editor textContainer]];
      newf.size.height += frame.size.height-[[self cell] drawingRectForBounds:frame].size.height;
   } else {
      newf.size.height = HUGE_VALF;
      newf.size = [[self cell] cellSizeForBounds:newf];
   }
   frame.size.height = newf.size.height;
   return frame.size;
}

So I put this into a category of NSTextField and did some runtime diddling with implementation pointers, but for other uses it could well be in a subclass.

The second problem is properly pushing down the views below the field when it is resized. The solution I ended up coding is a little too gnarly to post here, and it depends on the field and its sibling views being inside a custom NSView subclass with flipped coordinates… still, it seems to work well enough now, so I’ll leave it there and work on other stuff.