使用NSMenuItems从NSArray填充NSMenu - 需要替代建议

时间:2011-08-24 16:32:46

标签: objective-c cocoa nsarray nsmenuitem nsmenu

所以我有以下代码:

- (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中的子菜单项,并允许我根据所选的选项(在特定浏览器中)打开网址:

-(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;

并且出口链接到子菜单项,因为我已经创建了它的(parent?-terminology?)作为NSmenu,它不允许我访问它作为 - (void)setImage:(NSImage *) menuImage方法因为它不是NSMenuitem。现在我想也许我刚刚在这里做了一些奇怪的事情,技术上当你将“子菜单项”拖到界面构建器中它的NSMenuItem而不是NSMenu时,我的代码再次完美无缺地工作,除了我无法设置菜单的图像,我认为这是不行,但也许有类似的方式从NSArray读取以填充一组子菜单。

1 个答案:

答案 0 :(得分:0)

我能够通过更新nib文件中的图像来解决这个问题,因为nib认为它是一个nsmenuitem。

enter image description here