3

I have several NSAlert dialogs with different text. I want to adjust the alert window width to the text, so that the text don't wrap. Therefore I use this code to calculate the width of the string:

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

Then I try to adjust the window of the alert:

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];

This code works, but just for the first time, I call the method with this code. If I take another string and call the method again, the window will not resize (although the calculated width differentiate).

Any ideas, how I can resize the NSAlert window?

Lupurus
  • 3,618
  • 2
  • 29
  • 59
  • 5
    UI conventions on Mac OS X are to make alert dialogs taller for longer messages, not wider. This functionality should be automatic in NSAlert; you should not have to adjust anything yourself. –  Feb 11 '13 at 21:11
  • What if your string is really long? (In that case, would you have an alert that stretches across your display?) What if your string lengthens because you localized from, say, English, to a Romance language, which would make it as much as 30% longer? (Same problem, again.) Your question is intriguing, but the wrap is designed into NSAlert because, well, it doesn't know what it's going to have to display. – Extra Savoir-Faire Feb 11 '13 at 21:39
  • That's ok and I understand that, but I just display some filenames (including pathes). – Lupurus Feb 11 '13 at 21:42
  • P.S.: I would also insert a if condition to check, if the window is wider than the screen. The code above is not complete. I just wanted to test... – Lupurus Feb 11 '13 at 21:58
  • Displaying paths is a *really* good way to make your alert uncomfortably wide and/or tall; besides which, paths are just ugly no matter how you shape them. You should not be displaying any path to the user at all. A better way would be to use an NSPathControl, which you can put into an NSView that you would then use as the alert's accessory view. – Peter Hosey Feb 12 '13 at 07:02

1 Answers1

14

An NSAlert can be widened by adding an accessory view of sufficient width:

NSAlert *alert = [[[NSAlert alloc] init] autorelease];
alert.accessoryView = [[[NSView alloc] initWithFrame:NSMakeRect(0, 0, 500, 0)] autorelease];
D.McG.
  • 275
  • 4
  • 6