简体   繁体   English

在Swift for OSX的子类中管理事件处理

[英]Manage event handling in a subclass in Swift for OSX

I'm trying to implement a subclass of an NSSlider, which is supposed to handle modifiers keys events. 我正在尝试实现NSSlider的子类,该子类应该处理修饰键事件。 I've put this override func in the class: 我已经将此重写函数放在类中:

    override func flagsChanged(theEvent: NSEvent) {
    if (theEvent.modifierFlags.rawValue & NSEventModifierFlags.DeviceIndependentModifierFlagsMask.rawValue) == NSEventModifierFlags.AlternateKeyMask.rawValue {
        optionKeyPressed = true
        Swift.print("OptionKey is pressed")
    } else {
        optionKeyPressed = false
    }
}

And an initializer in: 还有一个初始化器:

    override init(frame: NSRect) {
        super.init(frame: frame)
    NSEvent.addLocalMonitorForEventsMatchingMask(.FlagsChangedMask) { (theEvent) -> NSEvent? in
        self.flagsChanged(theEvent)
        return theEvent
    }

Unfortunately, when I try to use my subclass in a storyboard, nothing happen: the init function is never called. 不幸的是,当我尝试在情节提要中使用子类时,什么也没发生:从未调用过init函数。

Pretty much a newbie in all these things, some guidance would be nice! 所有这些事情几乎都是新手,有一些指导很不错! Many thanks, 非常感谢,

Josh 乔希

You also need to implement the initWithCoder: initialiser, because when you use a class in a Storyboard, that initialiser is called: 您还需要实现initWithCoder:初始化程序,因为在情节提要中使用类时,该初始化程序称为:

required init?(coder: NSCoder) {
    super.init(coder: coder)
    NSEvent.addLocalMonitorForEventsMatchingMask(.FlagsChangedMask) { (theEvent) -> NSEvent? in
        self.flagsChanged(theEvent)
        return theEvent
    }
}

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

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