objective-c - NSAlert 调整窗口大小

标签 objective-c cocoa nsalert

我有几个带有不同文本的 NSAlert 对话框。我想根据文本调整警报窗口宽度,这样文本就不会换行。因此我使用这段代码来计算字符串的宽度:

NSSize size = [myString sizeWithAttributes:@{NSFontAttributeName: [NSFont systemFontOfSize:[NSFont systemFontSize]]}];

然后我尝试调整警报的窗口:

NSAlert *alert = [NSAlert alertWithMessageText:...
...
NSPanel *panel = alert.window;
NSRect frame = panel.frame;
float x = ((NSTextField*)[[((NSPanel*)(alert.window)).contentView subviews] objectAtIndex:5]).frame.origin.x;    //the x-position of the NSTextField
frame.size.width = size.width + x;
[alert.window setFrame:frame display:YES];

此代码有效,但这是我第一次使用此代码调用该方法。如果我使用另一个字符串并再次调用该方法,窗口将不会调整大小(尽管计算出的宽度有所不同)。

关于如何调整 NSAlert 窗口的大小,有什么想法吗?

最佳答案

可以通过添加足够宽度的附件 View 来加宽 NSAlert:

NSAlert *alert = [[[NSAlert alloc] init] autorelease];
alert.accessoryView = [[[NSView alloc] initWithFrame:NSMakeRect(0, 0, 500, 0)] autorelease];

关于objective-c - NSAlert 调整窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820335/

相关文章:

objective-c - NSAlert 提示输入由以 root 身份运行的进程生成的文本

objective-c - 在 NSPopover 中运行 NSAlert

c++ - Cocoa 应用程序(OS X 应用程序)中的 OpenCV

objective-c - cocoa 预定义调整鼠标光标大小?

cocoa - 我需要保留 NSAlert AlertDidEnd 的 contextInfo 吗?

cocoa - Xcodebuild 输出文件名

objective-c - Mac OS X 的 Cocoa 编程(第 3 版)已经过时了吗?

objective-c - NSComboBox 中的奇怪错误 : selectItemAtIndex does not work correctly when using data source

ios - 无需预取相关 PFObject 的 PFObject 子类指针赋值

ios - 用于管理观察者的 Objective-C 设计模式