Oliver Borchert Oliver Borchert - 4 months ago 40
Swift Question

OSX application without storyboard or xib files using Swift

Unfortunately, I haven't found anything useful on the Internet - I wanted to know, what code I actually have to type for initializing an application without using storyboard or XIB files in Swift. I know I have to have a

file called
. But I don't know what to write in there (like do I need autoreleasepool or something like that?). For example, what would I do for initializing an
and how would I add a
to the active window (iOS's similar
doesn't help). Thanks for any help ;)

I actually don't want to use
in front of the
. I'd rather know what exactly happens there and then do it myself.


if you don't want to have the @NSApplicationMain attribute, do:

  1. have a file main.swift
  2. add following top-level code:

    import Cocoa
    let delegate = AppDelegate() //alloc main app's delegate class
    NSApplication.sharedApplication().delegate = delegate //set as app's delegate
    // Old versions:
    // NSApplicationMain(C_ARGC, C_ARGV)
    NSApplicationMain(Process.argc, Process.unsafeArgv);  //start of run loop

the rest should be inside your app delegate. e.g.:

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {
    var newWindow: NSWindow?
    var controller: ViewController?

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        newWindow = NSWindow(contentRect: NSMakeRect(10, 10, 300, 300), styleMask: NSResizableWindowMask, backing: NSBackingStoreType.Buffered, defer: false)

        controller = ViewController()
        let content = newWindow!.contentView! as NSView
        let view = controller!.view


then you have a viewController

import Cocoa

class ViewController : NSViewController {
    override func loadView() {
        let view = NSView(frame: NSMakeRect(0,0,100,100))
        view.wantsLayer = true
        view.layer?.borderWidth = 2
        view.layer?.borderColor = NSColor.redColor().CGColor
        self.view = view