在Objective C中实现'show in finder'按钮

时间:2012-05-23 15:06:39

标签: objective-c macos cocoa finder

在我的应用程序中,我想创建一个'show in finder'按钮。我已经能够弄清楚如何弹出该目录的查找器窗口,但还没有弄清楚如何像操作系统那样突出显示该文件。

这可能吗?

4 个答案:

答案 0 :(得分:33)

NSArray *fileURLs = [NSArray arrayWithObjects:fileURL1, /* ... */ nil];
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:fileURLs];
被偷走了 Launch OSX Finder window with specific files selected

答案 1 :(得分:15)

您可以使用NSWorkspace方法-selectFile:inFileViewerRootedAtPath:,如下所示:

[[NSWorkspace sharedWorkspace] selectFile:fullPathString inFileViewerRootedAtPath:pathString];

答案 2 :(得分:3)

值得一提的是,owen的方法仅适用于osx 10.6或更高版本(参考:https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html)。

因此,如果你在老一代上写一些东西,那么最好以justin建议的方式进行,因为它尚未被弃用(尚未)。

答案 3 :(得分:0)

// 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()
    }

}