NSTextField width and autolayout

Yoav picture Yoav · Feb 1, 2013 · Viewed 7.2k times · Source

I am trying to create an NSTextField programmatically.

I want to use this NSTextField with auto layout, so its width will be defined automatically to display the entire line (there is only one line of text).

The problem is that textField.intrinsicContentSize and textField.fittingSize are both have -1 and 0 values for the horizontal coordinate, as the output of the code below is: textField.intrinsicContentSize={-1, 21} textField.fittingSize={0, 21}

The code:

NSTextField* textField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 10, 24)];    
NSString* str = @"One line of text here.";
[textField setStringValue: str];
[textField setTranslatesAutoresizingMaskIntoConstraints:NO];
[textField invalidateIntrinsicContentSize];

NSLog(@"textField.intrinsicContentSize=%@", NSStringFromSize(textField.intrinsicContentSize));
NSLog(@"textField.fittingSize=%@", NSStringFromSize(textField.fittingSize));

This makes the text field to have a zero width assigned by auto layout.

What should I do to get meaningful values for the fittingSize and intrinsicContentSize properties of the text field so they reflect the content of the text field?

Answer

Yoav picture Yoav · Feb 7, 2013

Another way to compute the text field optimal width without using fittingSize is using the following code (replacing John Sauer's sizeTextFieldWidthToFit method):

- (void) sizeTextFieldWidthToFit {
    [textField sizeToFit];
    CGFloat newWidth = NSWidth(textField.frame);
    textFieldWidthConstraint.constant = newWidth;
}

You can set the priority of textFieldWidthConstraint to be lower than the priority of another inequality constrain the represent your requirement to a minimal size of 25.