如何将 NSPanel 置于应用程序的中心 window

How to position NSPanel at center of app window

我对 Macos 开发还很陌生,网上几乎没有任何可用信息,但我似乎无法弄清楚如何将我的 NSpanel 放在我的应用程序的顶部中心 window。它在我整个屏幕的中央打开。

let dialog = NSOpenPanel()
            dialog.title = "Choose a file!"
            dialog.showsResizeIndicator = true;
            dialog.showsHiddenFiles = false;
            dialog.allowsMultipleSelection = false;
            dialog.canChooseDirectories = false;
            dialog.allowedFileTypes = ["py"];
            dialog.isFloatingPanel = false;

这是我当前的代码

您可以执行以下操作

let dialog = NSOpenPanel()
    dialog.title = "Choose a file!"
    dialog.showsResizeIndicator = true;
    dialog.showsHiddenFiles = false;
    dialog.allowsMultipleSelection = false;
    dialog.canChooseDirectories = false;
    dialog.allowedFileTypes = ["py"];

// here `window` is your document or main window (eg: `NSApp.mainWindow!`, etc.)
dialog.beginSheetModal(for: window) { result in
    if result == .OK {
        // do read a file
    }
}

如果将 NSOpenPanel 子类化并覆盖“中心”方法,则可以将面板放置在特定坐标上。

将面板放在屏幕的 top-left 上:

class MyOpenPanel: NSOpenPanel {    
override func center() {
    let rect = self.screen?.frame
    self.setFrameOrigin(NSPoint(x: 0, y: rect!.height - self.frame.height))
}

}