命令行 Swift 脚本的最小可行 GUI 是什么?

Dyl*_*lan 4 macos cocoa appkit swift

我的 Swift 脚本在 macOS 上需要一个小助手 GUI。它只需要一个文本输入字段和一个确定按钮。

我不想为了这个小弹出窗口而走整个臃肿的 Xcode 路线。但是,Apple 的文档让我失望,因为我的 NSWindow 没有捕获键盘输入。帮助!

Dyl*_*lan 7

不,多亏了苹果的文档,我终于想出了神奇的咒语???需要从接受键盘输入的命令行 Swift 应用程序启动一个简单的 AppKit/Cocoa GUI 。没有Xcode

这也是在 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()
Run Code Online (Sandbox Code Playgroud)

对于像我这样的菜鸟:这是整个应用程序,您可以使用它运行swift main.swift或编译它,swiftc main.swift并将生成的(仅 40 KB)可执行文件重命名为您想要在菜单栏中的任何内容。

  • 如果你在开头添加`#!/usr/bin/swift`,你也可以将它作为脚本运行。 (2认同)