使用Cocoa创建文件夹图标

3

在我的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”,但是图标并没有成功应用到文件夹中。我在代码上做错了什么吗?

谢谢。


试着看这里:https://dev59.com/mnRB5IYBdhLWcg3w6LN2。我猜你可能需要一个PNG文件作为图标。 - Shankar Raju
3
这个问题是关于如何通过编程设置Mac OS X图标。你提供的答案描述了iPhone图标的格式。 - Thomas Zoechling
1个回答

5
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;
        }
    }
}

1
不要忘记释放NSImage实例(假设您没有使用GC)。 - Peter Hosey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接