Search code examples
swiftmacosappkit

How to position NSPanel at center of app window


I'm very new to Macos development and there's barely any information available online but I cannot seem to figure out how to position my NSpanel at the top center of my app window. It opens in the center of my whole screen.

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;

this is my current code


Solution

  • You can do the following

    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
        }
    }