Swift下NSOpenPanel排除启动磁盘 或获取启动磁盘路径URL的咨询
获取启动磁盘路径URL
无需硬编码/Volumes/Macintosh HD,直接通过系统API获取启动磁盘的根URL,适配所有自定义命名的启动磁盘:
import Foundation func getBootVolumeRootURL() -> URL? { // 取本地域下的系统目录路径 guard let systemDirURL = try? FileManager.default.url( for: .systemDirectory, in: .localDomainMask, appropriateFor: nil, create: false ) else { return nil } // 系统目录的上一级就是启动磁盘根目录 return systemDirURL.deletingLastPathComponent().standardizedFileURL }
NSOpenPanel置灰禁用启动磁盘
通过NSOpenSavePanelDelegate的代理方法控制指定路径是否可选,实现启动磁盘置灰效果:
import AppKit class CustomOpenPanelManager: NSObject, NSOpenSavePanelDelegate { private let bootVolumeRoot = getBootVolumeRootURL() func presentOpenPanel() { let openPanel = NSOpenPanel() openPanel.delegate = self // 可根据需求自行配置openPanel的其他属性,例如canChooseDirectories、allowedContentTypes等 openPanel.runModal() } func panel(_ sender: Any, shouldEnable url: URL) -> Bool { guard let bootRoot = bootVolumeRoot else { return true } let standardizedURL = url.standardizedFileURL // 仅禁用启动磁盘根目录可选 if standardizedURL == bootRoot { return false } // 若需要完全禁用启动磁盘下的所有内容可选,替换上面的判断为下面的代码即可 // if standardizedURL.path.hasPrefix(bootRoot.path) { // return false // } return true } }
内容的提问来源于stack exchange,提问作者Fredo
相关产品推荐
相关产品推荐

