Vertical resizing of NSTextField when user resizes window

I have an NSTextField in a window view.

I have tried all the IB variants but cannot seem to achieve the following results:

There is a rather long suggestion in NSTextField - when the window is resized to a narrower width, the NSTextField also gets narrower, which pushes the text to the next line. However, any text that is pushed below the bottom of the NSTextField just gets cut off. I would like the NSTextField to expand its vertical size to accommodate taller text.

Can this be done automatically or should I watch for the window resize event and recalculate the NSTextField height?

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

EDIT 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];
}

      

+3


source to share


2 answers


Auto detection works at a higher level. I think you need to resize the textbox.

You can try sending -sizeToFit to the textbox, but that will probably expand horizontally rather than vertically. If that doesn't work, take a look at the -heightForWidth :: methods in the NS (Attributed) String + Geometrics category . Using this method, you can subclass NSTextField and override -sizeToFit to expand vertically. It would be great to include resizing in both setFrame: and setStringValue: so that it always maintains the appropriate height.



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

+2


source


Use this subclass to expand the height when the width changes:



@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

      

0


source







All Articles