You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:54:03