简体   繁体   中英

Cocoa: How to dynamically size the NSTextField?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM