context menu based on NSTableViewCell

后端 未结 7 726
余生分开走
余生分开走 2021-02-03 12:16

i would like to place a context menu onto a NSTableView. this part is done. what i would liek to do is to show different menu entries based on the content of the ri

7条回答
  •  情歌与酒
    2021-02-03 12:40

    Edit: The better way to do this than the below method is using delegate as shown in the accepted answer.

    You can subclass your UITableView and implement menuForEvent: method:

    -(NSMenu *)menuForEvent:(NSEvent *)event{
        if (event.type==NSRightMouseDown) {
            if (self.selectedColumn == 0 || self.selectedColumn ==1) {
                return nil;
            }else {
                //create NSMenu programmatically or get a IBOutlet from one created in IB
                NSMenu *menu=[[NSMenu alloc] initWithTitle:@"Custom"];
    
                //code to set the menu items
    
                //Instead of the following line get the value from your datasource array/dictionary
                //I used this as I don't know how you have implemented your datasource, but this will also work
                NSString *deleteValue = [[self preparedCellAtColumn:1 row:self.selectedRow] title]; 
    
                NSString *deleteString = [NSString stringWithFormat:@"Delete %@",deleteValue];
                NSMenuItem *deleteItem = [[NSMenuItem alloc] initWithTitle:deleteString action:@selector(deleteAction:) keyEquivalent:@""];
                [menu addItem:deleteItem];
    
                //save item
                //similarly 
                [menu addItem:saveItem];
    
                return menu;
            }
        }
        return nil;
    }
    

    That should do it. I haven't tried out the code though. But this should give you an idea.

提交回复
热议问题