だから私は次のコードを持っています:
- (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;
そして、アウトレットはサブメニュー項目にリンクされています。(parent? -terminology?) を NSmenu として作成したため、(void)setImage:(NSImage *)menuImage メソッドとしてこれにアクセスすることはできません。 NSMenuitem ではありません。技術的には、「サブメニュー項目」を NSMenu ではなく NSMenuItem であるインターフェイスビルダーにドラッグすると、メニューの画像を設定できないことを除いて、コードは問題なく動作します。これはいけないと思いますが、おそらく NSArray から読み取って一連のサブメニューを作成する同様の方法があります。