NSButton延迟NSMenu - Objective-C / Cocoa

时间:2012-02-08 15:18:16

标签: cocoa delay show nsbutton nsmenu

我想创建一个NSButton,在单击时发送动作,但按下1或2秒后会显示NSMenu。与此问题here完全相同,但由于答案无法解决我的问题,我决定再次提问。

例如,转到Finder,打开一个新窗口,浏览一些文件夹,然后单击后退按钮:转到上一个文件夹。现在单击并按住后退按钮:显示一个菜单。我不知道如何使用NSPopUpButton

执行此操作

4 个答案:

答案 0 :(得分:12)

使用NSSegmentedControl

通过向控件发送setMenu:forSegment:来添加菜单(将任何内容连接到IB中的menu插座都不会有效)。有一个动作连接到控件(这很重要)。

应该完全像你描述的那样工作。

答案 1 :(得分:6)

创建NSPopUpButton的子类并覆盖mouseDown / mouseUp个事件。

在调用mouseDown的实现之前暂时super事件延迟,并且仅在鼠标仍被按下时才会延迟。

在触发按钮mouseUp /之前,selectedMenuItem事件将nil设置为selectedMenuItemIndex(因此-1将为targetaction

唯一的另一个问题是处理快速点击,其中一次点击的计时器可能会在鼠标停止以供将来点击时触发。我没有使用NSTimer并使其无效,而是选择为mouseDown事件设置一个简单的计数器,并在计数器发生变化时进行纾困。

这是我在子类中使用的代码:

// MyClickAndHoldPopUpButton.h
@interface MyClickAndHoldPopUpButton : NSPopUpButton

@end

// MyClickAndHoldPopUpButton.m
@interface MyClickAndHoldPopUpButton ()

@property BOOL mouseIsDown;
@property BOOL menuWasShownForLastMouseDown;
@property int mouseDownUniquenessCounter;

@end

@implementation MyClickAndHoldPopUpButton

// highlight the button immediately but wait a moment before calling the super method (which will show our popup menu) if the mouse comes up
// in that moment, don't tell the super method about the mousedown at all.
- (void)mouseDown:(NSEvent *)theEvent
{
  self.mouseIsDown = YES;
  self.menuWasShownForLastMouseDown = NO;
  self.mouseDownUniquenessCounter++;
  int mouseDownUniquenessCounterCopy = self.mouseDownUniquenessCounter;

  [self highlight:YES];

  float delayInSeconds = [NSEvent doubleClickInterval];
  dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
  dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    if (self.mouseIsDown && mouseDownUniquenessCounterCopy == self.mouseDownUniquenessCounter) {
      self.menuWasShownForLastMouseDown = YES;
      [super mouseDown:theEvent];
    }
  });
}

// if the mouse was down for a short enough period to avoid showing a popup menu, fire our target/action with no selected menu item, then
// remove the button highlight.
- (void)mouseUp:(NSEvent *)theEvent
{
  self.mouseIsDown = NO;

  if (!self.menuWasShownForLastMouseDown) {
    [self selectItem:nil];

    [self sendAction:self.action to:self.target];
  }

  [self highlight:NO];
}

@end

答案 2 :(得分:4)

如果有人仍然需要这个,那么我的解决方案基于简单的NSButton,而不是分段控件。

子类NSButton并实现一个自定义mouseDown,它在当前运行循环中启动一个计时器。在mouseUp中,检查计时器是否未触发。在这种情况下,取消它并执行默认操作。

这是一种非常简单的方法,它适用于您可以在IB中使用的任何NSButton。

以下代码:

- (void)mouseDown:(NSEvent *)theEvent {
    [self setHighlighted:YES];
    [self setNeedsDisplay:YES];

    _menuShown = NO;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(showContextMenu:) userInfo:nil repeats:NO];

    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

- (void)mouseUp:(NSEvent *)theEvent {
    [self setHighlighted:NO];
    [self setNeedsDisplay:YES];

    [_timer invalidate];
    _timer = nil;

    if(!_menuShown) {
        [NSApp sendAction:[self action] to:[self target] from:self];
    }

    _menuShown = NO;
}

- (void)showContextMenu:(NSTimer*)timer {
    if(!_timer) {
        return;
    }

    _timer = nil;
    _menuShown = YES;

    NSMenu *theMenu = [[NSMenu alloc] initWithTitle:@"Contextual Menu"];

    [[theMenu addItemWithTitle:@"Beep" action:@selector(beep:) keyEquivalent:@""] setTarget:self];
    [[theMenu addItemWithTitle:@"Honk" action:@selector(honk:) keyEquivalent:@""] setTarget:self];

    [theMenu popUpMenuPositioningItem:nil atLocation:NSMakePoint(self.bounds.size.width-8, self.bounds.size.height-1) inView:self];

    NSWindow* window = [self window];

    NSEvent* fakeMouseUp = [NSEvent mouseEventWithType:NSLeftMouseUp
                                              location:self.bounds.origin
                                         modifierFlags:0
                                             timestamp:[NSDate timeIntervalSinceReferenceDate]
                                          windowNumber:[window windowNumber]
                                               context:[NSGraphicsContext currentContext]
                                           eventNumber:0
                                            clickCount:1
                                              pressure:0.0];

    [window postEvent:fakeMouseUp atStart:YES];

    [self setState:NSOnState];
}

我已经在我的GitHub上发布了working sample

答案 3 :(得分:1)

晚了聚会,但是这里有一些不同的方法,也将NSButton子类化:

///
/// @copyright © 2018 Vadim Shpakovski. All rights reserved.
///

import AppKit

/// Button with a delayed menu like Safari Go Back & Forward buttons.
public class DelayedMenuButton: NSButton {

  /// Click & Hold menu, appears after `NSEvent.doubleClickInterval` seconds.
  public var delayedMenu: NSMenu?
}

// MARK: -

extension DelayedMenuButton {

  public override func mouseDown(with event: NSEvent) {

    // Run default implementation if delayed menu is not assigned
    guard delayedMenu != nil, isEnabled else {
      super.mouseDown(with: event)
      return
    }

    /// Run the popup menu if the mouse is down during `doubleClickInterval` seconds
    let delayedItem = DispatchWorkItem { [weak self] in
      self?.showDelayedMenu()
    }
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Int(NSEvent.doubleClickInterval * 1000)), execute: delayedItem)

    /// Action will be set to nil if the popup menu runs during `super.mouseDown`
    let defaultAction = self.action

    // Run standard tracking
    super.mouseDown(with: event)

    // Restore default action if popup menu assigned it to nil
    self.action = defaultAction

    // Cancel popup menu once tracking is over
    delayedItem.cancel()
  }
}

// MARK: - Private API

private extension DelayedMenuButton {

  /// Cancels current tracking and runs the popup menu
  func showDelayedMenu() {

    // Simulate mouse up to stop native tracking
    guard
      let delayedMenu = delayedMenu, delayedMenu.numberOfItems > 0, let window = window, let location = NSApp.currentEvent?.locationInWindow,
      let mouseUp = NSEvent.mouseEvent(
        with: .leftMouseUp, location: location, modifierFlags: [], timestamp: Date.timeIntervalSinceReferenceDate,
        windowNumber: window.windowNumber, context: NSGraphicsContext.current, eventNumber: 0, clickCount: 1, pressure: 0
      )
    else {
        return
    }

    // Cancel default action
    action = nil

    // Show the default menu
    delayedMenu.popUp(positioning: nil, at: .init(x: -4, y: bounds.height + 2), in: self)

    // Send mouse up when the menu is on screen
    window.postEvent(mouseUp, atStart: false)
  }
}