user3748791
user3748791

Reputation: 41

Set level for NSAlert in Cocoa

In my application I've subclassed the NSWindow and set the window level as 25. Since the window level is 25 the alert box and error dialog box were being hidden by the window.

Is there any chance to set the level of NSAlert

Upvotes: 1

Views: 1164

Answers (2)

Ken Thomases
Ken Thomases

Reputation: 90671

You can do this, but it's a pretty gross kludge. The trick is to run a bit of code after runModal has started and set the alert window's level. You do the following before calling runModal to re-set the level after NSAlert has.

dispatch_async(dispatch_get_main_queue(), ^{
    [[NSApp modalWindow] setLevel:myLevel];
});

Upvotes: 0

Marek H
Marek H

Reputation: 5576

First of all. You shouldn't use magic numbers like 25.

There is a way to set window level but it's useless because runModal uses fixed windowLevel constant kCGModalPanelWindowLevel which is 8. You can verify it like this:

[self.window setLevel:25];
NSAlert *alert = [NSAlert alertWithMessageText:@"1" defaultButton:@"2" alternateButton:nil otherButton:nil informativeTextWithFormat:@"3"];
[alert runModal];

(lldb) po [alert.window valueForKey:@"level"]

8

#define NSModalPanelWindowLevel kCGModalPanelWindowLevel

Solution:

  1. Use sheet

    [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse response){ }];
    
  2. Swizzle implementation runModal with your own one.

  3. Recreate NSAlert functionality as a subclass of NSWindow/NSPanel (don't inherit NSAlert) and call showWindow: if you need to display it.

Upvotes: 4

Related Questions