macos - NSButton 带有鼠标向下/向上和按键向下/向上

标签 macos cocoa nsbutton

我需要一个 NSButton 来给我 2 个事件,一个是按下按钮时(NSOnState),一个是释放按钮时(NSOffState),到目前为止我已经让它与鼠标一起工作(拦截 mouseDown:事件)。但是使用键盘快捷键不起作用,它会经常触发 NSOnState 一次,然后在延迟后触发。有没有办法让按钮在按下时触发 NSOnState 并在释放时触发 NSOffState?

我当前的 NSButton 子类看起来像这样,不幸的是使用委托(delegate)工作:

-(void)awakeFromNib {
    [self setTarget:self];
    [self setAction:@selector(buttonAction:)];
}

-(void)mouseDown:(NSEvent *)theEvent {
    [_delegate button:self isPressed:YES];
    [super mouseDown:theEvent];
}

-(void)buttonAction:(id)sender {
    [_delegate button:self isPressed:NO];
}

最佳答案

可以使用 -sendActionOn::

将按钮设置为同时发送鼠标事件
[self.button sendActionOn: NSLeftMouseDownMask | NSLeftMouseUpMask];

类似地处理键盘事件似乎更困难。如果您不需要在按钮上突出显示的同时发生该事件,您可以覆盖 NSButton 的 -performKeyEquivalent: ,以便它可以例如发送操作两次。

- (BOOL) performKeyEquivalent: (NSEvent *) anEvent
{
    if ([super performKeyEquivalent: anEvent])
    {
        [self sendAction: self.action to: self.target];
        return YES;
    }
    return NO;
}

如果您确实同时需要该事件,我认为您需要使用自定义按钮单元格(通过创建 NSButtonCell 的子类并在初始化程序中设置按钮的单元格)并覆盖其 -highlight:withFrame :inView::

- (void)highlight:(BOOL)flag
        withFrame:(NSRect)cellFrame
           inView:(NSView *)controlView
{
    [super highlight: flag withFrame:cellFrame inView:controlView];

    if (flag)
    {
        // Action hasn't been sent yet.
    }
    else
    {
        // Action has been sent.
    }
}

关于macos - NSButton 带有鼠标向下/向上和按键向下/向上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25846924/

相关文章:

macos - 终端 PS1 中的断线修复

objective-c - 如何使用 setMessageBody 将 NSString 添加到电子邮件

objective-c - xcode 3.2.2 和 objective-c 2.0 和调试 : where are my object's property/instance variable values in debug?

objective-c - 如何将带有图像的项目添加到 NSMenu 中?

macos - 与 OS X 钥匙串(keychain)关联的不可见文件

cocoa - 如何使我的应用程序从 Finder 图标展开/折叠到 Finder 图标?

cocoa - 如何获得 NSButton 的首选大小?

objective-c - NSButton NSTrackingArea - 跟踪不起作用

swift - 以编程方式带有弹出窗口的 NSButton

macos - 通过brew安装后如何在Mac OS上使用Vim 7.4?