简体   繁体   中英

Swift 3/macOS: Open window on certain screen

Beginner question:

I am working on a macOS App with current Xcode 8.3.3 and Swift3. I am using MASShortcut to open a window by a shortcut that has been hidden by startup.

I use the following code on the shortcut event:

NSApplication.shared().windows.last!.makeKeyAndOrderFront(nil)
NSApplication.shared().activate(ignoringOtherApps: true)

For multiple monitor setups (I have two external displays attached to my MacBook), I want to specify the screen where the window pops up. I know there is NSScreen.screens() that gives back all available screens. But how do I use it for letting my window pop up on screen 1/2/3?

Thanks a lot!

Edit: Solved with the answer of @michael-doltermann:

I can iterate over NSScreen.screens() and access for example the midX/midY coords to create a NSPoint instance to replace my window.

var pos = NSPoint()
pos.x = NSScreen.screens()![myIndex].visibleFrame.midX)
pos.y = NSScreen.screens()![myIndex].visibleFrame.midY)
self.window?.setFrameOrigin(pos)

Each screen from NSScreen.screens() has a visibleFrame property that tells you the global frame rectangle.

You can then set your window origin to fit inside the frame rect coordinates of whatever screen you want. Objective-C answers can be seen here and here .

This does mean you have to write some code to specify the preferred window. In my own app, I take the global frame rectangles for each screen and then scale them way down into a NSView to display something that looks like the Monitors pane from System Preferences:

设置视频首选项

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM