Skip to content

Instantly share code, notes, and snippets.

@mcxiaoke
Forked from lucamarrocco/app.swift
Created May 24, 2016 04:13
Show Gist options
  • Save mcxiaoke/673e819046251e220b2e1903cc4251e3 to your computer and use it in GitHub Desktop.
Save mcxiaoke/673e819046251e220b2e1903cc4251e3 to your computer and use it in GitHub Desktop.
swift osx application without nib
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
let app: NSApplication
let controller: NSWindowController
init(app: NSApplication) {
self.app = app
self.controller = NiblessWindowController()
}
func applicationDidFinishLaunching(aNotification: NSNotification?) {
println("application started!")
controller.showWindow(nil)
app.activateIgnoringOtherApps(true)
}
func applicationWillTerminate(aNotification: NSNotification?) {
println("application terminated!")
}
func applicationShouldTerminateAfterLastWindowClosed() -> Bool {
return true
}
}
class Menu {
let app: NSApplication
init(app: NSApplication) {
self.app = app
self.app.menu = mainMenu()
}
func mainMenu() -> NSMenu {
let tree = [
"Apple": [
NSMenuItem(title: "Quit", action: "terminate:", keyEquivalent:"q"),
],
]
let result = NSMenu(title: "MainMenu")
for (title, items) in tree {
let menu = NSMenu(title: title)
if let item = result.addItemWithTitle(title, action: nil, keyEquivalent:"") {
result.setSubmenu(menu, forItem: item)
for item in items {
menu.addItem(item)
}
}
}
return result
}
}
class NiblessWindowController: NSWindowController {
required init(coder: NSCoder) {
fatalError("not implemented")
}
override init() {
super.init(window: nil)
let rect = NSMakeRect(0, 0, 480, 320)
let style = NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask
let window = NSWindow(contentRect:rect, styleMask:style, backing:.Buffered, defer:false)
window.title = "App"
self.window = window
}
}
let app = NSApplication.sharedApplication()
let delegate = AppDelegate(app: app)
app.delegate = delegate
let menu = Menu(app: app)
app.setActivationPolicy(.Regular)
atexit_b { app.setActivationPolicy(.Prohibited); return }
app.run()
.PHONY: build
build:
@DEVELOPER_DIR="/Applications/Xcode.app" SDKROOT="/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk" xcrun swiftc -o app app.swift && ./app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment