Search code examples
macoscocoanstextfield

Vertically resize NSTextField when window is resized by the user


I have an NSTextField within a View of a Window.

I have tried all IB options but I can't seem to achieve the following:

There is a pretty long sentence in the NSTextField - when the Window is resized to a narrower width the NSTextField also gets narrower - which pushes text onto the next line. However any text that gets pushed below the bottom of the NSTextField is simply cut off. I would like the NSTextField to expand its size vertically to accommodate the taller text.

Can this be done automatically or should I observe the Window resize event and recalculate the height of the NSTextField?

I need to support 10.7 and 10.8 and I have tried using both Autolayout and Autoresizing but to no avail.

EDIT - this is the code that worked based on Jerry's answer (and his category from Github):

-(void)setFrame:(NSRect)frameRect{

  NSRect myFrame = CGRectMake(frameRect.origin.x, frameRect.origin.y, frameRect.size.width, [self.stringValue heightForWidth:frameRect.size.width attributes:nil]);
  [super setFrame: myFrame];
}

Solution

  • Autolayout operates at a higher level. I think you need to resize the text field.

    You can try sending -sizeToFit to the text field, but that will probably expand horizontally instead of vertically. So if that doesn't work, look at the -heightForWidth:: methods in my NS(Attributed)String+Geometrics category. Using this method, you could subclass NSTextField and override -sizeToFit to expand vertically. It might be cool to incorporate the resizing into both setFrame: and setStringValue: so that it would always maintain an appropriate height.

    Autolayout should take over from there, moving and resizing sibling subviews as needed.