简体   繁体   English

按下修改键时以编程方式更改按钮文本和操作

[英]Programatically changing button text and actions when a modifier key is pressed

I would like to change the text of an NSButton when the ⌥ Option key is pressed - similar to the copy dialog when colliding files are detected on OS X which changes "Keep Both" to "Merge" when the option key is held. 我想在按下⌥Option键时更改NSButton的文本-与在OS X上检测到冲突文件时复制对话框类似,当按住Option键时将“同时保留”更改为“合并”。

In my case, I would like to change a button with text, say, "delete" to "quit" when I hold the option key. 就我而言,我想在按住选项键时将带有文本的按钮更改为“删除”到“退出”。 Additionally, its functionality should change in accordance with its title, much like the options in the Copy dialog. 此外,其功能应根据其标题进行更改,就像“复制”对话框中的选项一样。

Can this be done programatically in Swift? 可以在Swift中以编程方式完成吗?

You can subscribe using addLocalMonitorForEvents(matching:) and detect if option key pressed like this: 您可以使用addLocalMonitorForEvents(matching:)进行订阅,并检测是否按下了这样的选项键:

var optionKeyEventMonitor: Any? // property to store reference to the event monitor

// Add the event monitor
optionKeyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { event in
    if event.modifierFlags.contains(.option) {
        self.button.title = "copy"
        self.button.action = #selector(self.copyButtonClicked(_:))
    } else {
        self.button.title = "delete"
        self.button.action = #selector(self.deleteButtonClicked(_:))
    }  
    return event
}

@IBAction func copyButtonClicked(_ sender: Any) {
    Swift.print("Copy button was clicked!")
}

@IBAction func deleteButtonClicked(_ sender: Any) {
    Swift.print("Delete button was clicked!")
}

Remember to remove the event monitor when you are done: 完成后,请记住删除事件监视器:

deinit {
    if let eventMonitor = optionKeyEventMonitor {
        NSEvent.removeMonitor(eventMonitor)
    }
}

If you don't want a separate method called depending on the option key state, you can check modifierFlags when button is clicked instead: 如果您不希望根据选项键状态调用单独的方法,则可以单击按钮时检查ModifyFlags:

@IBAction func buttonClicked(sender: NSButton) {
    if NSEvent.modifierFlags().contains(.option) {
        print("option pressed")
    } else {
        print("option not pressed")
    }
}

In Swift 3 code: 在Swift 3代码中:

func optionKeyDown() -> Bool
{
    return NSEvent.modifierFlags().contains(NSEventModifierFlags.option)
}

if optionKeyDown()
{
    print ("do option code")
}
else
{
    print ("do normal code")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM