我使用以下代码来检索文件或文件夹的图标。然后在菜单中显示它们。我的问题是:有些文件,图标不显示(例如.txt
文件)。文件夹和一些其他文件的图标仍然显示。这个问题的可能原因是什么?
// menuItem.Title: display name for file/folder
// menuItem.Content: full path of file/url
let menuItem = NSMenuItem(title: item.Title, action: #selector(AppDelegate.openLocal(_:)), keyEquivalent: "")
let requiredAttributes = [URLResourceKey.effectiveIconKey]
if let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: item.Content), includingPropertiesForKeys: requiredAttributes, options: [.skipsHiddenFiles, .skipsPackageDescendants, .skipsSubdirectoryDescendants], errorHandler: nil) {
while let url = enumerator.nextObject() as? URL {
do {
let properties = try (url as NSURL).resourceValues(forKeys: requiredAttributes)
let icon = properties[URLResourceKey.effectiveIconKey] as? NSImage ?? NSImage()
menuItem.image = icon
}
catch {
}
}
}
最佳答案
我正在使用以下代码获取文件的图标。这非常可靠:
static func getIconForUrl(_ path: String) -> NSImage?
{
return NSWorkspace.shared.icon(forFile: path)
}
关于Swift:在 Mac 上检索文件图标时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785776/