简体   繁体   English

可可:如何动态调整NSTextField的大小?

[英]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? inputString的长度在编译时未知,因此如何调整标签的大小以使其全部适合一行并在给定inputString后将其居中?

I'm still new to Cocoa, so thanks for the help! 我还是可可的新手,非常感谢您的帮助!

Use NSControl's "- (void)sizeToFit" method. 使用NSControl的“-(void)sizeToFit”方法。 That will resize the textField according to the text in it. 这将根据其中的文本调整textField的大小。

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. 要使文本居中,可以在“界面生成器”中进行设置,并且在使用sizeToFit更新textField的大小时设置不会更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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