Skip to content

Instantly share code, notes, and snippets.

@habemus-papadum
Last active April 21, 2022 18:12
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save habemus-papadum/11f069b6d074f4bca794bf9399432533 to your computer and use it in GitHub Desktop.
Save habemus-papadum/11f069b6d074f4bca794bf9399432533 to your computer and use it in GitHub Desktop.
Single File Swift 3 Gui Sample
// A reminder to myself on how to quickly create a throw away gui app on OSX (i.e. a single file,
// w/o relying on XCode project templates
//Notes: In general it is hard to know how to create a Cocoa based gui without using XCode.
//This issue has existed for both Objective-C and now Swift
//Furthermore, Swift<-->Cocoa syntax has changed dramatically over various Swift versions,
//making stackoverflow posts unreliable
//This file provides a template for creating a throw away gui app
//Status: macOS only -- throw away apps for devices have many non-trivial aspects
//Status: This currenty works under swift 3 + package manager (just replace the main.swift generated
// with swift init --executable with this file
// However, it is not currently Swifty
//todo:
// add metal custom view or sprite kit demo to demonstrate using more frameworks
import Cocoa
print("Hello, world!")
//todo: remind myself what this does
NSApplication.shared()
//#1 status bar
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
statusItem.title = "Quit"
statusItem.action = #selector(NSApplication.terminate)
//#2 random window (not the typical pattern)
let window = NSWindow(contentRect: NSMakeRect(0, 0, 320, 200),
styleMask: .titled,
backing: .buffered,
defer: true)
window.orderFrontRegardless()
//#3 App delegate (more typical pattern)
class AppDel: NSObject, NSApplicationDelegate {
var mainWindow: NSWindow?
func applicationDidFinishLaunching(_ aNotification: Notification) {
print("Finished Launching")
let window = NSWindow(contentRect: NSMakeRect(800, 600, 320, 200),
styleMask: [.titled, .closable],
backing: .buffered,
defer: true)
window.orderFrontRegardless()
self.mainWindow = window
NSApp.activate(ignoringOtherApps: true)
}
func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool {
return true
}
}
NSApp.setActivationPolicy(.regular)
let del = AppDel()
NSApp.delegate = del
NSApp.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment