3
votes

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];
}
2
You might find some useful information here: stackoverflow.com/questions/10463680/…Monolo
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

2 Answers

2
votes

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.

0
votes

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