根据字符串的长度更新 NSTextField 的宽度

JH9*_*H95 5 macos xcode cocoa objective-c nstextfield

我想制作一个标签,根据它将显示的字符串值的大小更改其大小。目前我正在这样做:

[tfScroll setStringValue:strScoller];
[tfScroll sizeToFit];
Run Code Online (Sandbox Code Playgroud)

然而,这是行不通的。我错过了什么?

小智 5

如果您的 tfScroll 是 NSTextField:

CGRect frame = tfScroll.frame;
frame.size.width = tfScroll.attributedStringValue.size.width+somepoints;//(somepoints=8)
tfScroll.frame = frame;
Run Code Online (Sandbox Code Playgroud)

我没有找到 NSTextfield.contentSize。


Cai*_*uza 1

如果您尝试调整字段的高度,这可能有效:

CGRect frame = tfScroll.frame;
frame.size.height = tfScroll.contentSize.height;
tfScroll.frame = frame;
Run Code Online (Sandbox Code Playgroud)