在我的应用程序中,我想创建一个“在 Finder 中显示”按钮。
我已经能够弄清楚如何弹出该目录的 Finder 窗口,但还没有弄清楚如何像操作系统那样突出显示文件。
这可能吗?
NSArray *fileURLs = [NSArray arrayWithObjects:fileURL1, /* ... */ nil];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs];
从选择特定文件的 Launch OSX Finder 窗口中被盗
你可以使用这样的NSWorkspace
方法-selectFile:inFileViewerRootedAtPath:
:
[[NSWorkspace sharedWorkspace] selectFile:fullPathString inFileViewerRootedAtPath:pathString];
值得一提的是,欧文的方法仅适用于 osx 10.6 或更高版本(参考:https ://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html )。
因此,如果你写的东西要在老一代人身上运行,最好按照贾斯汀建议的方式来做,因为它还没有被弃用(还)。
// Place the following code within your Document subclass
// enable or disable the menu item called "Show in Finder"
override func validateUserInterfaceItem(anItem: NSValidatedUserInterfaceItem) -> Bool {
if anItem.action() == #selector(showInFinder) {
return self.fileURL?.path != nil;
} else {
return super.validateUserInterfaceItem(anItem)
}
}
// action for the "Show in Finder" menu item, etc.
@IBAction func showInFinder(sender: AnyObject) {
func showError() {
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = "Sorry, the document couldn't be shown in the Finder."
alert.runModal()
}
// if the path isn't known, then show an error
let path = self.fileURL?.path
guard path != nil else {
showError()
return
}
// try to select the file in the Finder
let workspace = NSWorkspace.sharedWorkspace()
let selected = workspace.selectFile(path!, inFileViewerRootedAtPath: "")
if !selected {
showError()
}
}