我在上一堂学生课:
@interface student : NSObject{
NSString *name;
NSDate *date;
}我有一个学生列表的NSMutableArray,我将它绑定到一个NSPopUpButton上,如下所示
content : studentArray,arrangedObjects内容值: studentArray,arrangedObjects,name
现在我可以像这样获取学生对象:
-(IBAction)studentPopupItemSelected:(id)sender
{
NSPopUpButton *btn = (NSPopUpButton*)sender;
int index = [btn indexOfSelectedItem];
student *std = [studentArray objectAtIndex:index];
NSLog(@"%@ => %@", [std name], [std date]);
}有什么方法可以直接从NSPopUpButton获取学生对象吗?像这样:
NSPopUpButton *btn = (NSPopUpButton*)sender;
student *std = (student *)[btn objectValueOfSelectedItem];发布于 2012-08-23 00:08:24
你做这件事的方式很好。还有另一种方法,但不一定更好。
基本上,弹出按钮包含一个菜单,并且在菜单中有菜单项。
在菜单项上有一个名为representedObject的属性,您可以使用它来创建与学生的关联。
因此,您可以通过创建菜单项并将其添加到菜单中来手动构建弹出按钮。
发布于 2012-08-22 23:52:13
我相信你的做法是最好的。由于NSPopUpButton是由您的数组填充的,因此它实际上并不包含对象,它只知道它在哪里。就个人而言,我会使用
-(IBAction)studentPopupItemSelected:(id)sender {
student *std = [studentArray objectAtIndex:[sender indexOfSelectedItem]];
NSLog(@"%@ => %@", [std name], [std date]);
}看过NSPopUpButton上的文档后,我确信这是获取对象的最有效的方法。
发布于 2012-12-16 05:51:28
我通过使用"NSMenuDidSendActionNotification“解决了这个问题,一旦用户在NSMenu的NSPopUpButton中选择了合适的NSMenuItem,就会发送这个has。
您可以注册观察者,例如"awakeFromNib“,如下所示
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(popUpSelectionChanged:)
name:NSMenuDidSendActionNotification
object:[[self myPopUpButton] menu]];如果你有多个NSPopUpButtons,你可以为每一个注册一个观察者。不要忘记在dealloc中删除观察者:
[[NSNotificationCenter defaultCenter] removeObserver: self];在popUpSelectionChanged中,您可以检查标题,这样您就可以知道是哪个菜单实际发送了通知。可以在属性检查器的界面生成器中设置标题。
- (void)popUpSelectionChanged:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
if ([[[[info objectForKey:@"MenuItem"] menu] title] isEqualToString:@"<title of menu of myPopUpButton>"]) {
// do useful things ...
}
}https://stackoverflow.com/questions/12075195
复制相似问题