Created
October 2, 2018 06:36
-
-
Save anongit/c759de0e54b648566a90f9bc56ac99e0 to your computer and use it in GitHub Desktop.
Hello world GUI window application, updated to Swift 4 from: http://www.rockhoppertech.com/blog/swift-script-to-create-a-cocoa-window/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env swift | |
import Cocoa | |
// due to the new constraint syntax | |
@available(OSX 10.11, *) | |
class AppDelegate: NSObject, NSApplicationDelegate { | |
let window = NSWindow() | |
let windowDelegate = WindowDelegate() | |
func applicationDidFinishLaunching(_ notification: Notification) { | |
window.setContentSize(NSSize(width:600, height:600)) | |
window.styleMask.formUnion([.titled, .closable, .miniaturizable, .resizable]) | |
window.level = .normal | |
window.delegate = windowDelegate | |
window.isOpaque = false | |
window.title = "Window with a button" | |
let contentView = window.contentView! | |
let button = NSButton(frame: NSRect(x:0, y:0, width:10, height:10)) | |
button.bezelStyle = .regularSquare | |
button.title = "Click Me" | |
button.action = #selector(AppDelegate.myAction(_:)) | |
contentView.addSubview(button) | |
// autolayout | |
button.translatesAutoresizingMaskIntoConstraints = false | |
var c = button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) | |
c.isActive = true | |
c.identifier = "to center y" | |
c = button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor) | |
c.isActive = true | |
c.identifier = "to center x" | |
c = button.widthAnchor.constraint(equalToConstant: 200) | |
c.isActive = true | |
c.identifier = "width" | |
c = button.heightAnchor.constraint(equalToConstant: 50) | |
c.isActive = true | |
c.identifier = "height" | |
window.center() | |
window.makeKey() | |
window.orderFrontRegardless() | |
} | |
@objc | |
func myAction(_ sender: AnyObject) { | |
print("my action") | |
} | |
} | |
class WindowDelegate: NSObject, NSWindowDelegate { | |
private func windowWillClose(notification: Notification) { | |
NSApplication.shared.terminate(0) | |
} | |
} | |
if #available(OSX 10.11, *) { | |
let app = NSApplication.shared | |
let appDelegate = AppDelegate() | |
app.delegate = appDelegate | |
app.run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment