SwiftUI 使用键盘快捷键调用 NSPopover [英] SwiftUI Invoke NSPopover with Keyboard Shortcut

查看:51
本文介绍了SwiftUI 使用键盘快捷键调用 NSPopover的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用适用于 macOS Big Sur 的 SwiftUI 构建菜单栏应用程序,但不知道如何使用键盘快捷键打开弹出窗口(该应用程序的主窗口,因为它是一个菜单栏应用程序).我希望用户能够通过按 Command + [a letter] 来查看窗口,而不管他们在计算机上做什么(当然只要应用程序是打开的).下面是控制弹出框的主要函数和代码:

I'm building a menu bar application with SwiftUI for macOS Big Sur and can't figure out how to open the popover (the app's main window, since it's a menu bar app) with a keyboard shortcut. I want users to be able to view the window by pressing Command + [a letter] regardless of what else they're doing on their computer (as long as the application is open of course). Here are the main functions and code that control the popover:

@main
struct MenuBarPopoverApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        Settings{
            EmptyView()
        }
        .commands {
            MenuBarPopoverCommands(appDelegate: appDelegate)
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
    var popover = NSPopover.init()
    var statusBarItem: NSStatusItem?
    var contentView: ContentView!

    override class func awakeFromNib() {}
    
    func applicationDidFinishLaunching(_ notification: Notification) {
        print("Application launched")
        NSApplication.shared.activate(ignoringOtherApps: true)
        
        contentView = ContentView()
        popover.animates = false
        popover.behavior = .transient
        
        let contentVc = NSViewController()
        contentVc.view = NSHostingView(rootView: contentView.environmentObject(self))
        popover.contentViewController = contentVc

        statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        let itemImage = NSImage(named: "statusBarIcon")
        itemImage?.isTemplate = true
        statusBarItem?.button?.image = itemImage
        statusBarItem?.button?.action = #selector(AppDelegate.togglePopover(_:))
    }
    
    @objc func showPopover(_ sender: AnyObject?) {
        if let button = statusBarItem?.button {
            NSApplication.shared.activate(ignoringOtherApps: true)
            popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
        }
    }

    @objc func closePopover(_ sender: AnyObject?) {
        popover.performClose(sender)
    }

    @objc func togglePopover(_ sender: AnyObject?) {
        if popover.isShown {
            closePopover(sender)
        } else {
            showPopover(sender)
        }
    }
}

还有 MenuBarPopoverCommands(应用程序的主要部分是一个文本编辑器,所以我有一堆与之相关的键盘快捷键):

And the MenuBarPopoverCommands (the main part of the app is a text editor, so I have a bunch of keyboard shortcuts relating to that):

struct MenuBarPopoverCommands: Commands {
    
    let appDelegate: AppDelegate
    
    init(appDelegate: AppDelegate) {
        self.appDelegate = appDelegate
    }
    
    var body: some Commands {
        CommandMenu("Edit") {
            Section {
                Button("Cut") {
                    appDelegate.contentView.editCut()
                }.keyboardShortcut(KeyEquivalent("x"), modifiers: .command)
                
                Button("Copy") {
                    appDelegate.contentView.editCopy()
                }.keyboardShortcut(KeyEquivalent("c"), modifiers: .command)
                
                Button("Paste") {
                    appDelegate.contentView.editPaste()
                }.keyboardShortcut(KeyEquivalent("v"), modifiers: .command)
                
                Button("Undo") {
                    appDelegate.contentView.undo()
                }.keyboardShortcut(KeyEquivalent("z"), modifiers: .command)
                
                Button("Redo") {
                    appDelegate.contentView.redo()
                }.keyboardShortcut(KeyEquivalent("z"), modifiers: [.command, .shift])
                
                Button("Bold") {
                    appDelegate.contentView.bold()
                }.keyboardShortcut(KeyEquivalent("b"), modifiers: .command)
                
                Button("Italic") {
                    appDelegate.contentView.italic()
                }.keyboardShortcut(KeyEquivalent("i"), modifiers: .command)
                
                Button("Select All") {
                    appDelegate.contentView.editSelectAll()
                }.keyboardShortcut(KeyEquivalent("a"), modifiers: .command)
            }
        }
    }
}

推荐答案

Swift 5 解决方案已在 https://stackoverflow.com 中提出/a/58225397/3984522.然而,有一个很好的包,它可以完成这项工作 https://github.com/soffes/HotKey在几行代码中:

Swift 5 solution was presented in https://stackoverflow.com/a/58225397/3984522. However, there's a nice package, which does the job https://github.com/soffes/HotKey in a couple of lines of code:


import SwiftUI
import HotKey

@main
struct MenuBarPopoverApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        Settings{
            EmptyView()
        }
        .commands {
            MenuBarPopoverCommands(appDelegate: appDelegate)
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
    var popover = NSPopover.init()
    var statusBarItem: NSStatusItem?
    var contentView: ContentView!
    let hotKey = HotKey(key: .x, modifiers: [.control, .shift])  // Global hotkey
    
    override class func awakeFromNib() {}
    
    func applicationDidFinishLaunching(_ notification: Notification) {
        print("Application launched")
        NSApplication.shared.activate(ignoringOtherApps: true)
        
        contentView = ContentView()
        popover.animates = false
        popover.behavior = .transient
        
        let contentVc = NSViewController()
        contentVc.view = NSHostingView(rootView: contentView.environmentObject(self))
        popover.contentViewController = contentVc
        
        statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        let itemImage = NSImage(systemSymbolName: "eye", accessibilityDescription: "eye")
        itemImage?.isTemplate = true
        statusBarItem?.button?.image = itemImage
        statusBarItem?.button?.action = #selector(AppDelegate.togglePopover(_:))
        
        hotKey.keyUpHandler = {                                 // Global hotkey handler
            self.togglePopover()
        }
    }
    
    @objc func showPopover(_ sender: AnyObject? = nil) {
        if let button = statusBarItem?.button {
            NSApplication.shared.activate(ignoringOtherApps: true)
            popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
        }
    }
    
    @objc func closePopover(_ sender: AnyObject? = nil) {
        popover.performClose(sender)
    }
    
    @objc func togglePopover(_ sender: AnyObject? = nil) {
        if popover.isShown {
            closePopover(sender)
        } else {
            showPopover(sender)
        }
    }
}

这篇关于SwiftUI 使用键盘快捷键调用 NSPopover的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆