Creating a Cocoa application without NIB files

前端 未结 11 758
余生分开走
余生分开走 2020-12-04 10:24

Yes, I know this goes against the whole MVC principle!

However, I\'m just trying to whip up a pretty trivial application - and I\'ve pretty much implemented it. Howe

11条回答
  •  悲哀的现实
    2020-12-04 10:34

    7 years too late to the party, but a bit simpler single file code

    #import 
    
    @interface AppDelegate : NSObject  {
        NSWindow* window;
    }
    @end
    
    @implementation AppDelegate : NSObject
    - (id)init {
        if (self = [super init]) {
            window = [NSWindow.alloc initWithContentRect: NSMakeRect(0, 0, 200, 200)
                                               styleMask: NSWindowStyleMaskTitled | NSWindowStyleMaskClosable
                                                 backing: NSBackingStoreBuffered
                                                   defer: NO];
        }
        return self;
    }
    
    - (void)applicationWillFinishLaunching:(NSNotification *)notification {
        window.title = NSProcessInfo.processInfo.processName;
        [window cascadeTopLeftFromPoint: NSMakePoint(20,20)];
        [window makeKeyAndOrderFront: self];
    }
    
    @end
    
    int main(int argc, const char * argv[]) {
        NSApplication* app = NSApplication.sharedApplication;
        app.ActivationPolicy = NSApplicationActivationPolicyRegular;
        NSMenuItem* item = NSMenuItem.new;
        NSApp.mainMenu = NSMenu.new;
        item.submenu = NSMenu.new;
        [app.mainMenu addItem: item];
        [item.submenu addItem: [[NSMenuItem alloc] initWithTitle: [@"Quit " stringByAppendingString: NSProcessInfo.processInfo.processName] action:@selector(terminate:) keyEquivalent:@"q"]];
        AppDelegate* appDelegate = AppDelegate.new; // cannot collapse this and next line because .dlegate is weak
        app.delegate = appDelegate;
        (void)app.run;
        return 0;
    }
    

提交回复
热议问题