Cocoa: How to dynamically size the NSTextField?

4.2k views Asked by At

I created a label:

NSTextField *label = [NSTextField alloc] initWithFrame:NSMakeRect(50, 50, 100, 50)];
    [txtField setStringValue:inputString];
    [txtField setEditable:false];

The length of inputString is unknown at compile time, so how can I resize the label so that it fits all in one line and center it after giving it the inputString?

I'm still new to Cocoa, so thanks for the help!

1

There are 1 answers

0
AProgrammer On

Use NSControl's "- (void)sizeToFit" method. That will resize the textField according to the text in it.

To make text centered, you can do it in the Interface Builder and that settings will not change as you update the size of the textField using sizeToFit.