使用Cocoa为文件夹创建图标 [英] Using Cocoa to create an icon for a folder

查看:242
本文介绍了使用Cocoa为文件夹创建图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 beginSheetForDirectory: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]; 

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

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?

谢谢。

推荐答案

NSWorkspace 方法就像魅力一样。也许您的图标格式无效?

我尝试 setIcon:使用Finder图标:

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

这篇关于使用Cocoa为文件夹创建图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆