简体   繁体   中英

How can I programmatically display a window on a specific screen (i.e., main display as opposed to external displays) in Swift 5? [MacOS; Xcode 15]

I am facing difficulty presenting my app window on a specific screen (ie, the main display as opposed to my external display). The reason why I want to display my app on the main display is that I would like to blank out my external display later on by using CGDisplayCapture(CGDirectDisplayID(2)) .

I found several suggestions and implementations as follows.

Swift 3/macOS: Open window on certain screen

How to change the NSScreen a NSWindow appears on

Show window on multiple displays on os x

how to move NSWindow to a particular screen?

However, I cannot figure out how to actualize this in Swift 5 . This could be because the previous posts got outdated. For example, the following my code (based on Swift 3/macOS: Open window on certain screen ) does not work... it does not do anything.

override func viewDidLoad() {
    super.viewDidLoad()
    
    //set up the main display as the display where window shows up
    let screens = NSScreen.screens
    var pos = NSPoint()
    pos.x = screens[0].visibleFrame.midX
    pos.y = screens[0].visibleFrame.midY
    self.view.window?.setFrameOrigin(pos)

I would appreciate it if I could hear how to implement this.

The ViewController isn't the right place to be doing this. Either use a WindowController and put the relevant code in windowDidLoad , or, if you really want a view that causes its parent window to fill the primary display, override viewDidMoveToWindow on your view. (The latter would be a bit odd in most cases IMO.)

Thanks to the question posed by @Willeke, I was able to use the following code to display the window on the main screen (as opposed to external displays). I just needed to use DispatchQueue.main.async {} .

   override func viewDidLoad() {
         super.viewDidLoad()
         DispatchQueue.main.async {
             
             //set up the main display as the display where window shows up
             let screens = NSScreen.screens
             var pos = NSPoint()
             pos.x = screens[0].visibleFrame.midX
             pos.y = screens[0].visibleFrame.midY
             self.view.window?.setFrameOrigin(pos)
             
         }
    }

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