簡體   English   中英

如何以編程方式在 Swift 5 中的特定屏幕(即主顯示器而不是外部顯示器)上顯示 window? [蘋果系統; Xcode 15]

[英]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]

我在特定屏幕上展示我的應用程序 window 時遇到了困難(即主顯示器而不是我的外部顯示器)。 我想在主顯示器上顯示我的應用程序的原因是我想稍后通過使用CGDisplayCapture(CGDirectDisplayID(2))來清空我的外部顯示器。

我發現了如下幾個建議和實現。

Swift 3/macOS:在特定屏幕上打開 window

如何更改出現 NSWindow 的 NSScreen

在 os x 的多個顯示器上顯示 window

如何將 NSWindow 移動到特定屏幕?

但是,我無法弄清楚如何在Swift 5中實現這一點。 這可能是因為以前的帖子已經過時了。 例如,以下我的代碼(基於Swift 3/macOS: Open window on certain screen )不起作用......它沒有做任何事情。

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)

如果我能聽到如何實現這一點,我將不勝感激。

ViewController不是執行此操作的正確位置。 使用WindowController並將相關代碼放在windowDidLoad中,或者,如果您真的想要一個導致其父 window 填充主顯示的視圖,請在您的視圖上覆蓋viewDidMoveToWindow (在大多數情況下,后者在 IMO 中會有點奇怪。)

感謝@Willeke 提出的問題,我能夠使用以下代碼在主屏幕上顯示 window(而不是外部顯示器)。 我只需要使用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)
             
         }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM