1

首先我的代码:

   - (NSMenu*)sourceList:(PXSourceList*)aSourceList menuForEvent:(NSEvent*)theEvent item:(id)item
    {
     if ([theEvent type] == NSRightMouseDown || ([theEvent type] == NSLeftMouseDown && ([theEvent modifierFlags] & NSControlKeyMask) == NSControlKeyMask)) {
      NSMenu * m = [[NSMenu alloc] init];  
      if (item != nil) {
       NSLog(@"%@",[item title]);

       [m addItemWithTitle:[item title] action:@selector(press:) keyEquivalent:@""]; // problem. i want to give "item" as an argument.....

       for (NSMenuItem* i in [m itemArray]) {
        [i setTarget:self];
       }
      } else {
       [m addItemWithTitle:@"clicked outside" action:nil keyEquivalent:@""];
      }
      return [m autorelease];
     }
     return nil;
    }
-(void) press:(id)sender{
 NSLog(@"PRESS");
}

我想用选择器item作为我的press:方法的参数。

非常感谢你 :)

PS:我是为 Mac 而不是 iPhone 做这个。

4

2 回答 2

6

NSMenuItem 有一个名为 的方法setRepresentedObject:,菜单项对象将作为sender参数传递给press:方法。

So you need to adjust your code to call setRepresentedObject: with the item that goes with each NSMenuItem, and then in press: you can call [sender representedObject] to get that item back.

于 2011-01-15T17:37:27.337 回答
4

我几乎可以肯定,@selector(press:)消息中包含的“发件人”参数NSMenuItem.

所以:

- (void) press:(id)sender {
  NSLog(@"sender: %@", sender);
}

那应该记录发件人是NSMenuItem被选中的人。

编辑误解了问题...

您希望在item选择某个 menuItem 时检索该对象。这很容易。做就是了:

NSMenuItem * menuItem = [m addItemWithTitle:[item title] action:@selector(press:) keyEquivalent:@""];
[menuItem setTarget:self];
[menuItem setRepresentedObject:item];

然后在你的press:方法...

- (void) press:(id)sender {
  //sender is the NSMenuItem
  id selectedItem = [sender representedObject];
}
于 2011-01-15T17:32:25.930 回答