Search code examples
objective-ccocoansviewnsevent

NSEvent clickCount ignore single click method if double click occurs


Is it possible to ignore the first click if a double click is detected?

The following example will still log the one click even before the two clicks. I want to ignore the single click if there is a double click event.

- (void)mouseUp:(NSEvent *)theEvent {

    if (theEvent.clickCount > 1) {
        NSLog(@"two clicks %ld", theEvent.clickCount);
    } else {
        NSLog(@"one click %ld", theEvent.clickCount);
    }
} 

The purpose of doing this, is when the user single clicks in an NSView I want to perform a method that makes another view or window to appear. However, if the user double clicks inside the NSView then I want a different view or window to appear. The following steps outline this work flow:

  • user single clicks the NSView to make ViewA appear
  • user double clicks the NSView to make ViewB appear

The problem that I'm having is the single click is always detected therefore ViewA will always appear. But I do not want ViewA to appear if there is a double click, I just want ViewB to appear when there is a double click.


Solution

  • Unless, you can go back in time, you will need to cancel the previous single tap event somehow.

    1. The easiest way: delay the execution on single tap event, and cancel it out if double click is detected.

      [self performSelector:@selector(singleTap) withObject:nil afterDelay:[NSEvent doubleClickInterval]];
      
      /// cancel out
      [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTap) object:nil];
      
    2. Or, you can execute single tap action immediately, and write a code to cancel it out if double click is detected. This should be very easy too. Because, if it's hard, there might be something wrong with your UX design.