微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

objective-c – 使用Cocoa为文件夹创建图标

在我的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”,但图标未成功应用于该文件夹.我在代码中做错了吗?

谢谢.

解决方法

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐