Search code examples
cocoamouseeventnsoutlineview

Mouse Event in Outline View


I have a window which contains a split view. One of the "splits" contains an outline view. I have a window controller (which is the file owner for the window's XIB). The window controller is the delegate and data source of the outline view.

When I call the -(void)mouseDown:(NSEvent *)e method in the window controller only the toolbar responds to the method - the outline view does not.

How do I get the mouse events, e.g. the mouseDown, of the outline view?


Solution

  • To get the mouse event of the outline view:

    1. Subclass the outline view.
      • In Interface Builder (IB) > Library panel > Classes tab select NSOutlineView
      • Right-click NSOutlineView and select "New Subclass..."
      • Complete the following pop-up windows selecting "Generate Source Files" and add the fils to your project
      • Select the NSOutlineView
      • In Inspector Panel > Identity tab > Class Identity > Class select your new class
    2. Implement your mouse event method

      • In Xcode > your new subclass of your outline view > the implementation (.m) file type your method e.g.

        (void)mouseDown:(NSEvent *)theEvent {
            /* CODE YOU WANT EXECUTED WHEN MOUSE IS CLICKED */
            NSLog(@"Mouse down occurred");
            // call this to get the usual behaviour of your outline
            // view in addition to your custom code
            [super mouseDown:theEvent];
        }
        

    It may be useful to know that one can get mouse events by using [NSEvent modifierFlags]. This is will work not just for the outline view but for views throughout the app. For example, in the window controller (referred to in the question) I could include code like:

    if ([NSEvent modifierFlags] == NSAlternateKeyMask) { // if the option key is being pressed
                /*SOME CODE*/
    }