所以我有以下代码:
- (void)addSupportLinksMenuItems
{
NSString *subMenuTitle;
NSString *getURL;
if (!supportLinks) {
supportLinks = [[NSArray alloc] initWithArray:[settings objectForKey:@"supportLinks"]];
}
for(NSDictionary *object in supportLinks){
// A couple of Keys in the Dict inside the Array
subMenuTitle = [object objectForKey:@"subMenuTitle"];
getURL = [object objectForKey:@"getURL"];
NSInteger n = [ supportLinks indexOfObject:object];
NSInteger menuTag = n +255;
//[ supportLinkItem setImag
supportLinkArrayItem = [supportLinkItem
insertItemWithTitle:subMenuTitle
action:@selector(openSupportLink:)
keyEquivalent:@""
atIndex:n];
// Set a menu tag to programatically update in the future
[ supportLinkArrayItem setTag:menuTag];
[ supportLinkArrayItem setToolTip:getURL];
[ supportLinkArrayItem setTarget:self];
}
//supportLinkItem
}
这会从 NSArray 动态生成子菜单项,并允许我根据选择的选项(在特定浏览器中)打开 url:
-(IBAction)openSupportLink:(id)sender
{
NSLog(@"Was passed Menu: %@",sender);
NSInteger menuTag = [sender tag];
NSInteger n = menuTag - 255;
NSString *getURL = [[supportLinks objectAtIndex:n] objectForKey:@"getURL"];
[self openPageInSafari:getURL];
}
- (void)openPageInSafari:(NSString *)url
{
NSDictionary* errorDict;
NSAppleEventDescriptor* returnDescriptor = NULL;
NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
[NSString stringWithFormat:
@"\
tell app \"Safari\"\n\
activate \n\
make new document at end of documents\n\
set URL of document 1 to \"%@\"\n\
end tell\n\
",url]];
returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
[scriptObject release];
}
我的问题是,虽然这似乎很好用,但我想为 NSMenu supportLinkItem 设置一个图像,这是我的 .h 文件的样子:
IBOutlet NSMenu *supportLinkItem;
NSMenuItem *supportLinkArrayItem;
并且出口链接到子菜单项,因为我已将其(父项?-术语?)创建为 NSmenu,它不允许我作为 - (void)setImage:(NSImage *)menuImage 方法访问它它不是一个 NSMenuitem。现在我想也许我在这里做了一些奇怪的事情,从技术上讲,当你将“子菜单项”拖到界面构建器中时,它是一个 NSMenuItem 而不是 NSMenu,我的代码再次完美运行,除了我无法设置菜单的图像,我认为这是不行的,但也许有类似的方法可以从 NSArray 中读取来填充一组子菜单。