开发者

Using Cocoa to create an icon for a folder

In my Mac OS application, I'm prompting a user to create a new folder. I would like to apply an icon to this folder using Cocoa when it is created. Currently, to create the folder, I'm using the following code:

- (IBAction)browseFiles:(id)sender
{
    NSOpenPanel *oPanel = [[NSOpenPanel openPanel] retain];
    [oPanel setCanChooseDirectories:YES];
    [oPanel setCanChooseFiles:NO];
    [oPanel setDelegate:self];
    [oPanel setCanCreateDirectories:YES];
    [oPanel beginSheetForDir开发者_如何学Cectory:NSHomeDirectory()
                              file:nil
                             types:nil
                    modalForWindow:nil
                     modalDelegate:self
                    didEndSelector:@selector(filePanelDidEnd:
                                             returnCode:
                                             contextInfo:)
                       contextInfo:nil];
}

After choosing a directory, the user clicks a confirm button that calls a function with the following method:

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

While the piece of code above does return "YES", the icon is not successfully applied to the folder. Am I doing something wrong in my code?

Thanks.


The NSWorkspace method works like a charm here. Maybe your icon is in an invalid format?
I tried setIcon: using the Finder icon:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜