NSOpenPanel 无法获得焦点

Sla*_*agt 5 command-line nsopenpanel swift macos-catalina

首先,我对 Swift 完全陌生,如果我的问题看起来微不足道,我很抱歉。

我想要一个非常简单的命令行程序,它打开一个对话框来选择文件或文件夹。该工具不得运行带有在 Dock 中弹跳的图标的实际完整应用程序,而是运行一些微妙的东西。就是这样。我所做的正是产生了这一点,只是面板无法获得焦点。当我单击面板时,它保持灰色。有趣的是,可以单击按钮或拖放文件,但无法探索文件系统。键盘事件也不会被捕获。

import AppKit

let dialog = NSOpenPanel()

dialog.title                   = "Choose a .tif file or a folder";
dialog.showsResizeIndicator    = true;
dialog.showsHiddenFiles        = false;
dialog.canChooseDirectories    = true;
dialog.canCreateDirectories    = true;
dialog.allowsMultipleSelection = false;
dialog.allowedFileTypes        = ["tif", "tiff"];
dialog.isFloatingPanel         = true;

if (dialog.runModal() == NSApplication.ModalResponse.OK)
{
  let result = dialog.url // Pathname of the file
  if (result != nil)
  {
    let path = result!.path
    print(path)
    exit(0)
  }
}

exit(1)
Run Code Online (Sandbox Code Playgroud)

如何显示行为正常的 NSOpenPanel?即:可以获得焦点,可以与鼠标和键盘交互,...

没有焦点的 NSOpenPanel

aya*_*aio 5

在这种情况下(没有窗口的应用程序),您需要将 NSApplication 激活策略设置为.accessory激活面板(也有,.regular但它会显示 Dock 图标和菜单栏)。

import AppKit

NSApplication.shared.setActivationPolicy(.accessory)

let dialog = NSOpenPanel()

dialog.title                   = "Choose a .tif file or a folder"
dialog.showsResizeIndicator    = true
dialog.showsHiddenFiles        = false
dialog.canChooseDirectories    = true
dialog.canCreateDirectories    = true
dialog.allowsMultipleSelection = false
dialog.allowedFileTypes        = ["tif", "tiff"]
dialog.isFloatingPanel         = true


if (dialog.runModal() == NSApplication.ModalResponse.OK)
{
    let result = dialog.url // Pathname of the file
    if (result != nil)
    {
        let path = result!.path
        print(path)
        exit(0)
    }
}

exit(1)
Run Code Online (Sandbox Code Playgroud)