Handling keyboard shortcuts and managing focus in macOS applications using Swift can enhance user experience by providing quicker access to functionalities. Below is an example of how to create a macOS application that responds to keyboard shortcuts and manages focus on views effectively.
import Cocoa
@main
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.closable, .titled, .resizable],
backing: .buffered, defer: false)
window.center()
window.setFrameAutosaveName("Main Window")
window.title = "Keyboard Shortcuts Example"
window.makeKeyAndOrderFront(nil)
let menu = NSMenu()
let appMenuItem = NSMenuItem()
menu.addItem(appMenuItem)
NSApp.mainMenu = menu
let appMenu = NSMenu(title: "Application")
appMenu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApp.terminate(_:)), keyEquivalent: "q"))
appMenuItem.submenu = appMenu
// Register global keyboard shortcut
let eventMask: NSEvent.EventTypeMask = [.keyDown]
NSEvent.addGlobalMonitorForEvents(matching: eventMask) { (event) in
if event.modifierFlags.contains(.command) && event.keyCode == 15 { // 'R' key
print("Command-R pressed")
// You can add your functionality here.
}
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?