Distinguishing a single click from a double click in Cocoa on the Mac

后端 未结 5 1070
一向
一向 2021-02-01 21:05

I have a custom NSView (it\'s one of many and they all live inside an NSCollectionView — I don\'t think that\'s relevant, but who knows). When I click

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-01 21:32

    Add two properties to your custom view.

    // CustomView.h
    @interface CustomView : NSView {
      @protected
        id      m_target;
        SEL     m_doubleAction;
    }
    @property (readwrite) id target;
    @property (readwrite) SEL doubleAction;
    
    @end
    

    Overwrite the mouseUp: method in your custom view.

    // CustomView.m
    #pragma mark - MouseEvents
    
    - (void)mouseUp:(NSEvent*)event {
        if (event.clickCount == 2) {
            if (m_target && m_doubleAction && [m_target respondsToSelector:m_doubleAction]) {
                [m_target performSelector:m_doubleAction];
            }
        }
    }
    

    Register your controller as the target with an doubleAction.

    // CustomController.m
    - (id)init {
        self = [super init];
        if (self) {
            // Register self for double click events.
            [(CustomView*)m_myView setTarget:self];
            [(CustomView*)m_myView setDoubleAction:@selector(doubleClicked:)];
        }
        return self;
    }
    

    Implement what should be done when a double click happens.

    // CustomController.m
    - (void)doubleClicked:(id)sender {
      // DO SOMETHING.
    }
    

提交回复
热议问题