简体   繁体   中英

How to open a new window in a Cocoa application on launch

I have created a cocoa application (not document based) and have the default MyAppDelegate class and the MainMenu nib file. I have also created a new nib which contains a window called Splash and a window controller class (NSWindowController) called SplashWindowController.

What I would like is that when the application starts instead of the MainMenu nib window opening I would like to open the Splash window.

I think that I have to create an instance of my SplashWindowController in my AppDelegate class and then instantiate the window and set it to front. However I have tried several things like including a reference to the SplashWindowController.h file in my AppDelegate class and also adding an object to my MainMenu nib and setting its class to be SplashWindowController. But have had no luck with either.

If anybody out there could help me with this one it would be much appreciated as have been at this (what seems like a simple task) for the best part of a day.

Thanks in advance.

You can simply combine both windows into one .xib file.

ExampleAppDelegate.h

#import <Cocoa/Cocoa.h>

@interface ExampleAppDelegate : NSObject <NSApplicationDelegate> {
    IBOutlet id splash;
    IBOutlet id window;
}

- (IBAction)closeSplashButton:(id)sender;
- (void)closeSplash;

@end

ExampleAppDelegate.m

#import "ExampleAppDelegate.h"

@implementation ExampleAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [NSTimer scheduledTimerWithTimeInterval:5.0
                                     target:self
                                   selector:@selector(closeSplash)
                                   userInfo:nil
                                    repeats:NO];    
}

- (IBAction)closeSplashButton:(id)sender {
    [self closeSplash];
}

- (void)closeSplash {
    [splash orderOut:self];
    [window makeKeyAndOrderFront:self];
    [NSApp activateIgnoringOtherApps:YES];
}

@end

MainMenu.xib

  • Add NSWindow (Title: Splash)
  • Add NSButton to the Splash window
  • Connect both IBOutlets to the corresponding windows
  • Connect the button to the corresponding IBAction
  • Enable 'Visible at Launch' for the splash window (using the Inspector)
  • Disable 'Visible at Launch' for the main window (using the Inspector)

在此输入图像描述

Result

At launch only the splash window is visible. The splash window automatically closes after 10 seconds. The user can close the splash window directly by pressing the button. The main windows shows up after closing the splash window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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