文件类型的Cocoa图标?

14

如果我有一个文件,我可以通过执行类似以下的操作来获取图标:

NSImage *iconImage = [[NSWorkspace sharedWorkspace] iconForFile: @"myFile.png"];

但如果我只想获取特定文件类型的图标(例如与png文件相关联的图标,而不需要已存在的“myFile.png”),我不确定该如何做到这一点。

非常感谢您的建议!

4个回答

27

哈,我完全错过了那个。谢谢你指出来给我。 - Kyle
2
Swift 示例:NSWorkspace.sharedWorkspace().iconForFileType("txt") - Leslie Godwin
不幸的是,确定文件的UTI,然后生成通用图标并不能保证与iconForFile(Cocoa)相同的结果。例如,如果我在Finder的“获取信息”窗格中粘贴自定义图标到文件夹或文件上,iconForFile将使用该图标,而较新的Swift方法则不会。 - utt50

4
您可以首先确定文件类型(UTI),然后将其传递给获取图标的方法:
NSString *fileName = @"lemur.jpg"; // generic path to some file
CFStringRef fileExtension = (__bridge CFStringRef)[fileName pathExtension];
CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);

NSImage *image = [[NSWorkspace sharedWorkspace]iconForFileType:(__bridge NSString *)fileUTI];

1

这是Swift 5版本的Dave DeLong的最初回答

icon(forFile:)

Returns an image containing the icon for the specified file.

Declaration

func icon(forFile fullPath: String) -> NSImage

Parameters

fullPath
The full path to the file.

icon(forFileType:)

Returns an image containing the icon for files of the specified type.

Declaration

func icon(forFileType fileType: String) -> NSImage

Parameters

fileType
The file type, which may be either a filename extension, an encoded HFS file type, or a universal type identifier (UTI).

谢谢你的反馈!如果你觉得我的答案不够有用,我很想了解你认为我应该如何写出更有用的回答。请留下评论帮助我改进! - Ky -

0

这是 PetrV的答案Swift 5 版本:

public extension NSWorkspace {

    /// Returns an image containing the icon for files of the same type as the file at the specified path.
    ///
    /// - Parameter filePath: The full path to the file.
    /// - Returns: The icon associated with files of the same type as the file at the given path.
    func icon(forFileTypeAtSamplePath filePath: String) -> NSImage? {
        let fileExtension = URL(fileURLWithPath: filePath).pathExtension
        guard
            let unmanagedFileUti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
                                                                         fileExtension as CFString, nil),
            let fileUti = unmanagedFileUti.takeRetainedValue() as String?
            else {
                assertionFailure("Should've gotten a UTI for \(fileExtension)")
                return nil
        }

        return NSWorkspace.shared.icon(forFileType: fileUti)
    }
}

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