2

我正在开发一个 swift Mac OS 应用程序,它只在状态栏(带有弹出框)中工作,Application is background only设置为true.

在弹出框内,用户可以与按钮交互以保存图像,更具体地说,触发了以下功能:

@IBAction func saveImage(sender: NSButton) {
    self.closePopover()

    let dialog = NSSavePanel()

    let date = Date()
    let formattedDate = getFormattedDate(date: date, format: "yyyy-MM-dd")
    let formattedTime = getFormattedDate(date: date, format: "HH.mm.ss")
    dialog.level = .modalPanel
    dialog.title                    = "Choose a destination"
    dialog.nameFieldStringValue     = "Screenshot \(formattedDate) at \(formattedTime)"
    dialog.showsResizeIndicator     = true
    dialog.showsHiddenFiles         = false
    dialog.canCreateDirectories     = true
    dialog.allowedFileTypes         = ["png"]

    if (dialog.runModal() == .OK) {
        // Pathname of the file
        if let result = dialog.url {
            self.screenshot!.savePNGRepresentationToURL(url: result)
        }
    } else {
        // User clicked on "Cancel"
        return
    }
}

问题是:

  • 如果我输入Application is background only= true
    我无法与 NSSavePanel 交互(无法更改save as字段)并且如果我在该框中写入,则文本将写入我正在交互的最后一个应用程序中(焦点并不真正在模式上) .
  • 如果我放Application is background only= false
    NSSavePanel 工作得很好,但这不是一个好的解决方案,因为我不想让图标出现在 Dock 中

所以这个问题显然与Application is background only但我没有找到一种方法来拥有两者:

  • 扩展坞中没有应用程序图标
  • 与 NSSavePanel 的良好交互
4

1 回答 1

0

I solved using the NSApplication.shared.setActivationPolicy method like this:

@IBAction func saveImage(sender: NSButton) {
    self.closePopover()

    NSApplication.shared.setActivationPolicy(.regular)

    let dialog = NSSavePanel()

    let date = Date()
    let formattedDate = getFormattedDate(date: date, format: "yyyy-MM-dd")
    let formattedTime = getFormattedDate(date: date, format: "HH.mm.ss")
    dialog.level = .modalPanel
    dialog.title                    = "Choose a destination"
    dialog.nameFieldStringValue     = "Screenshot \(formattedDate) at \(formattedTime)"
    dialog.showsResizeIndicator     = true
    dialog.showsHiddenFiles         = false
    dialog.canCreateDirectories     = true
    dialog.allowedFileTypes         = ["png"]

    if (dialog.runModal() == .OK) {
        // Pathname of the file
        if let result = dialog.url {
            self.screenshot!.savePNGRepresentationToURL(url: result)
        }
    } else {
        // User clicked on "Cancel"
    }

    NSApplication.shared.setActivationPolicy(.accessory)
}
于 2020-02-12T12:52:03.737 回答