【问题标题】:SwiftUI NSPathControl open finder location when clicking icons单击图标时SwiftUI NSPathControl打开查找器位置
【发布时间】:2021-11-04 16:17:26
【问题描述】:

我已经包装了 NSPathControl 以在我的 Mac OS SwiftUI 应用程序中使用,但我不知道如何使路径的大小更小,或者如何让单个路径在单击时在 Finder 中打开位置。

这是包装器:

struct PathView: NSViewRepresentable {
    typealias pathViewNSView = NSPathControl
    var configuration = { (view: pathViewNSView) in }
    
    func makeNSView(context: NSViewRepresentableContext<PathView>) -> NSPathControl {
        pathViewNSView()
    }
    func updateNSView(_ nsView: NSPathControl, context: NSViewRepresentableContext<PathView>) {
        configuration(nsView)
    }
}

我使用这样的视图:

PathView { view in
    view.url = URL(fileURLWithPath: "/Volumes/Users/myfolder", isDirectory: true)
}

我知道使用 NSWorkspace.shared.selectFile 在 Finder 中打开路径,但不确定如何使用包装的 NSPathControl 执行此操作。

【问题讨论】:

    标签: macos swiftui appkit nspathcontrol


    【解决方案1】:

    您可以将Coordinator 模式与NSViewRepresentable 一起使用:

    struct PathView: NSViewRepresentable {
        var configuration = { (view: NSPathControl) in }
        
        func makeNSView(context: NSViewRepresentableContext<PathView>) -> NSPathControl {
            let pathControl = NSPathControl()
            pathControl.target = context.coordinator
            pathControl.action = #selector(Coordinator.action)
            return pathControl
        }
        func updateNSView(_ nsView: NSPathControl, context: NSViewRepresentableContext<PathView>) {
            configuration(nsView)
        }
        
        func makeCoordinator() -> Coordinator {
            return Coordinator()
        }
        
        class Coordinator : NSObject, NSPathControlDelegate {
            @objc func action(sender: NSPathControl) {
                if let url = sender.clickedPathItem?.url {
                    print(url)
                    NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: url.path)
                }
            }
        }
    }
    

    注意:我实际上并没有使用任何 NSPathControlDelegate 方法——这只是为了表明它也可以扩展为委托

    【讨论】:

    • 哇,非常感谢 - 我今晚会研究协调器模式!
    • 查看后我发现我不能真正影响 PathControl 视图的大小而不严重搞乱。如果路径被截断并像 Finder 窗口一样在悬停时打开会很方便。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2013-02-05
    相关资源
    最近更新 更多