How do you add context senstive menu to NSOutlineView (ie right click menu)

前端 未结 5 1984
终归单人心
终归单人心 2020-12-25 14:16

How do you add the ability to right click on a row in an NSOutlineView so you can say delete an object or some other activity. (ie Like when you right click on a folder in t

5条回答
  •  伪装坚强ぢ
    2020-12-25 15:12

    In your menuForEvent method you can find out which row the click occurred on. You can pass that as a parameter to your defaultMenu method -- maybe call it defaultMenuForRow:

    -(NSMenu*)menuForEvent:(NSEvent*)evt 
    {
        NSPoint pt = [self convertPoint:[evt locationInWindow] fromView:nil];
        int row=[self rowAtPoint:pt];
        return [self defaultMenuForRow:row];
    }
    

    Now you can build the menu for the row you found in the event...

    -(NSMenu*)defaultMenuForRow:(int)row
    {
        if (row < 0) return nil;
    
        NSMenu *theMenu = [[[NSMenu alloc] 
                                    initWithTitle:@"Model browser context menu"] 
                                    autorelease];
        [theMenu insertItemWithTitle:@"Add package" 
                              action:@selector(addSite:) 
                       keyEquivalent:@"" 
                             atIndex:0];
        [theMenu insertItemWithTitle:[NSString stringWithFormat:@"Remove '%i'", row] 
                              action:@selector(removeSite:) 
                       keyEquivalent:@"" 
                             atIndex:0];
        // you'll need to find a way of getting the information about the 
        // row that is to be removed to the removeSite method
        // assuming that an ivar 'contextRow' is used for this
        contextRow = row;
    
        return theMenu;        
    }
    

    Also, as already mentioned in the comments, you really shouldn't use the NS-prefix on your own classes. There is a potential for a clash in the future plus it will confuse everybody that is looking at your code - including yourself :)

    Hope this helps...

提交回复
热议问题