检查keyDown event.modifierFlags会产生错误 [英] Checking keyDown event.modifierFlags yields error

查看:263
本文介绍了检查keyDown event.modifierFlags会产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Im子类化NSTextView和覆盖keyDown。我想检测命令键组合。 Command-L。

Im subclassing NSTextView and overriding keyDown. I want to detect command-key-combinations. Command-L, for example.

Apple的文档表示您只需使用NSEventModifierFlags.CommandKeyMask即可修改符标记(在传递的NSEvent中)。

Apple's documentation indicates that you simply and the modifier flags (in the passed NSEvent) with NSEventModifierFlags.CommandKeyMask.

当我这样做:

let ck = NSEventModifierFlags.CommandKeyMask

我收到一个奇怪的错误:

I receive an odd error:

Binary operator '&' cannot be applied to two 'NSEventModifierFlags' operands.

什么交易?这是swift 2.0,xcode 7。

What's the deal? This is swift 2.0, xcode 7.

谢谢!

推荐答案


Apple的文档表明您只需修饰符标志

仍然指C和Objective-C。 Swift使用 OptionSetType code> ,它不使用按位运算符检查标志。

The documentation is still referring to C and Objective-C. Swift uses OptionSetType, which does not use bitwise operators for checking flags.

而是使用 contains()方法检查一个或多个标志:

Instead, use the contains() method to check for one or more flags:

    if theEvent.modifierFlags.contains(.CommandKeyMask) {
        NSLog("command key down")
    }

    if theEvent.modifierFlags.contains(.AlternateKeyMask) {
        NSLog("option key down")
    }

    if theEvent.modifierFlags.contains([.CommandKeyMask, .AlternateKeyMask]) {
        NSLog("command and option keys down")
    }


$ b b

要检查单个键,使用 intersect 过滤掉任何不需要的标志,然后使用 == 以检查单个标志:

To check for a single key, use intersect to filter out any unwanted flags, then use == to check for a single flag:

    let modifierkeys = theEvent.modifierFlags.intersect(.DeviceIndependentModifierFlagsMask)

    if modifierkeys == .CommandKeyMask {
        NSLog("Only command key down")
    }

这篇关于检查keyDown event.modifierFlags会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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