3

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];
}
petenelson
  • 460
  • 2
  • 15
  • 1
    You might find some useful information here: http://stackoverflow.com/questions/10463680/how-to-let-nstextfield-grow-with-the-text-in-auto-layout – Monolo Feb 13 '13 at 17:09
  • Thanks Monolo - was actually better to use Jerry's category combined with -(NSSize)intrinsicContentSize as I didn't need to explicitly set the frame and therefore it kept Auto Layout in order. Life is good. – petenelson Feb 15 '13 at 12:17

2 Answers2

2

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.

Jerry Krinock
  • 4,860
  • 33
  • 39
  • Yes that works - thanks Jerry. I did the NSTextField subclass and overrode setFrame: I'll need to hone this a bit but the proof of concept is there - thanks - and thanks for your category as well for calculating height. I have added some detail above – petenelson Feb 13 '13 at 17:15
0

Use this subclass to expand height on width change:

@interface MyTextField : NSTextField

@property (nonatomic, assign) BOOL insideDeepCall;

@end

@implementation MyTextField

- (void)layout
{
  [super layout];

  if (!self.insideDeepCall) {
    self.insideDeepCall = YES;
    self.preferredMaxLayoutWidth = self.frame.size.width-4;
    [self.superview layout];
    self.insideDeepCall = NO;
  }
}

@end
k06a
  • 17,755
  • 10
  • 70
  • 110