【问题标题】:Using Cocoa to create an icon for a folder使用 Cocoa 为文件夹创建图标
【发布时间】:2011-08-10 00:09:51
【问题描述】:

在我的 Mac OS 应用程序中,我提示用户创建一个新文件夹。我想在创建时使用 Cocoa 将图标应用于此文件夹。目前,要创建文件夹,我使用以下代码:

- (IBAction)browseFiles:(id)sender
{
    NSOpenPanel *oPanel = [[NSOpenPanel openPanel] retain];
    [oPanel setCanChooseDirectories:YES];
    [oPanel setCanChooseFiles:NO];
    [oPanel setDelegate:self];
    [oPanel setCanCreateDirectories:YES];
    [oPanel beginSheetForDirectory:NSHomeDirectory()
                              file:nil
                             types:nil
                    modalForWindow:nil
                     modalDelegate:self
                    didEndSelector:@selector(filePanelDidEnd:
                                             returnCode:
                                             contextInfo:)
                       contextInfo:nil];
}

选择目录后,用户单击确认按钮,该按钮使用以下方法调用函数:

bool set = [[NSWorkspace sharedWorkspace] setIcon:[NSImage imageNamed:@"icon.icns"] forFile:path options:NSExcludeQuickDrawElementsIconCreationOption]; 

虽然上面的代码确实返回“YES”,但图标并未成功应用于文件夹。我在我的代码中做错了吗?

谢谢。

【问题讨论】:

  • 试试看这里:stackoverflow.com/questions/475410/…。我猜你可能需要一个 PNG 文件作为图标。
  • 这个问题是关于以编程方式设置 Mac OS X 图标的。您链接的答案描述了 iPhone 图标应具有的格式。

标签: objective-c cocoa macos icons


【解决方案1】:

NSWorkspace 方法在这里就像一个魅力。也许您的图标格式无效?
我尝试使用 Finder 图标 setIcon:

- (IBAction)setFolderIcon:(id)sender
{
    NSOpenPanel* openPanel = [NSOpenPanel openPanel];
    [openPanel setCanChooseFiles:NO];
    [openPanel setCanChooseDirectories:YES];
    switch([openPanel runModal])
    {
        case NSFileHandlingPanelOKButton:
        {
            NSURL* directoryURL = [openPanel directoryURL];
            NSImage* iconImage = [[NSImage alloc] initWithContentsOfFile:@"/System/Library/CoreServices/Finder.app/Contents/Resources/Finder.icns"];
            BOOL didSetIcon = [[NSWorkspace sharedWorkspace] setIcon:iconImage forFile:[directoryURL path] options:0];
            NSLog(@"%d", didSetIcon);
            [iconImage release];
        }
        case NSFileHandlingPanelCancelButton:
        {
            return;
        }
    }
}

【讨论】:

  • 别忘了释放 NSImage 实例(假设你没有使用 GC)。
  • 谢谢彼得。更新了答案。
猜你喜欢
  • 2011-03-27
  • 1970-01-01
  • 2012-04-26
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
相关资源
最近更新 更多