NSButton 带有延迟的 NSMenu - Objective-C/Cocoa

12
我想创建一个NSButton,当它被点击时发送一个动作,但当按下1或两秒钟时显示一个NSMenu。与这个问题相同,但由于那个答案没有解决我的问题,所以我决定再次提问。
例如,打开Finder,打开新窗口,在一些文件夹中浏览,然后单击后退按钮:您将回到上一个文件夹。现在点击并按住后退按钮:一个菜单被显示。我不知道如何使用NSPopUpButton来实现这一点。
4个回答

14

使用NSSegmentedControl

通过向控件发送setMenu:forSegment:来添加菜单(在IB中连接到menu插座不起作用)。确保与控件连接一个操作(这很重要)。

应该与您描述的完全一样。


1
很遗憾,你不能为NSSegmentedControl设置自定义高度 - 我需要将该菜单附加到一个大按钮上。 - zrslv

6
如果有人仍需要此功能,这是我的解决方案,基于普通的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上发布了一个工作示例


6

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

mouseDown事件在调用super的实现之前延迟片刻,只有当鼠标仍然按下时才调用。

mouseUp事件将selectedMenuItem设置为nil(因此selectedMenuItemIndex将为-1)再触发按钮的target/action

唯一的问题是如何处理快速点击,其中一个点击的计时器可能会在鼠标按下某个未来的点击时触发。我选择使用mouseDown事件的一个简单计数器来代替使用NSTimer并使其无效。

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

// 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

1
太棒了!这正是我在寻找的。可惜在 App Kit 中没有标准控件来处理这种情况(这很奇怪,因为苹果在自己的许多应用程序中都使用了这种 UI 约定)。 - aapierce
1
对于 delayInSeconds,考虑使用 NSEvent.doubleClickInterval 而不是常量 0.2。这将根据用户的鼠标操作偏好调整延迟时间。对于双击时间短的用户来说,速度更快,延迟更少;对于双击时间长的用户来说,速度更慢,延迟更多。 - Graham Miln

2

虽然有点晚,但这里提供一种不同的方法,也是通过子类化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)
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接