Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the minimally-viable GUI for command-line Swift scripts?

I need a little helper GUI for my Swift script on macOS. It just needs a text entry field and an OK button.

I don't want to go the whole bloated Xcode route just for this little popup. However, Apple's documentation fails me because keyboard input isn't captured by my NSWindow. Help!

like image 373
dsharhon Avatar asked Dec 22 '22 20:12

dsharhon


1 Answers

No thanks to Apple's documentation, I finally figured out the magical incantations 🧙‍♂️ needed to launch a simple AppKit/Cocoa GUI from a command-line Swift app that accepts keyboard input. Without Xcode!

This is also needed to accept text input in WKWebViews.

// main.swift // Dylan Sharhon // Tested on Catalina, Nov 2019
import AppKit // import Cocoa if you also need Foundation functionality

let app = NSApplication.shared
app.setActivationPolicy(.regular) // Magic to accept keyboard input and be docked!

let window = NSWindow.init(
  contentRect: NSRect(x: 300, y: 300, width: 200, height: 85),
  styleMask:   [
    NSWindow.StyleMask.titled     // Magic needed to accept keyboard input
  ],
  backing:     NSWindow.BackingStoreType.buffered,
  defer:       false
)
window.makeKeyAndOrderFront(nil)  // Magic needed to display the window

// Text input field
let text = NSTextField.init(string: "")
text.frame = NSRect(x: 10, y: 45, width: 180, height: 25)
window.contentView!.addSubview(text)

// Button
class Target {
  @objc func onClick () {         // Magic @objc needed for the button action
    print(text.stringValue)       // Goes to stdout
    exit(0)
  }
}
let target = Target()
let button = NSButton.init(
  title:  "OK",
  target: target,
  action: #selector(Target.onClick)
)
button.frame = NSRect(x:50, y:10, width:100, height:30)
window.contentView!.addSubview(button)

app.run()

To noobs like me: This is the entire app and you can run it with swift main.swift or compile it with swiftc main.swift and rename the resulting (merely 40 KB) executable to whatever you want to be in the menubar.

like image 145
dsharhon Avatar answered Feb 02 '23 00:02

dsharhon