2017-03-15 15 views
2

私はフローティングウィンドウでCocoaアプリケーションを作っています。フローティングウィンドウは、メイン画面の中央に、メイン画面の1/4のサイズで表示されます。次スウィフトは、私のアプリケーションの本質である:これは、このようなパネルを生産する私のCocoaアプリケーションは、NSScreenの解像度の変更をどのように通知できますか?

import Cocoa 
@NSApplicationMain 
class AppDelegate: NSObject, NSApplicationDelegate { 
    var panel: NSPanel! 
    func applicationDidFinishLaunching(_ aNotification: Notification) { 
     let screenRect:CGRect = NSScreen.main()!.frame 
     panel = NSPanel(
      contentRect: NSRect(
       x: screenRect.width/4, 
       y: screenRect.height/4, 
       width: screenRect.width/2, 
       height: screenRect.height/2 
      ), 
      styleMask: NSWindowStyleMask.nonactivatingPanel, 
      backing: NSBackingStoreType.buffered, 
      defer: false 
     ) 
     panel.alphaValue = 0.5 
     panel.backgroundColor = NSColor.red 
     panel.level = Int(CGWindowLevelForKey(CGWindowLevelKey.maximumWindow)) 
     panel.orderFront(nil) 
    } 
} 

CORRECTLY POSITIONED

をするとき、メイン画面の解像度の変更の問題が発生します。これを表示する1つの方法は、「システム環境設定」>「ディスプレイ」に進み、解像度を「スケーリング」および「より多くのスペース」に設定することです。そうした後、パネルは次のようになります。あなたが見ることができるように解像度が変更された後

INCORRECTLY POSITIONED AFTER RESOLUTION CHANGE

は、パネルの位置が正しくありません。私はパネルの位置を維持することを望みます:画面の中央と1/4のサイズ。これを行うには、パネルのサイズと位置を変更できるように、画面解像度(のframeのプロパティ)が変更されたときを検出します。

NSScreenframeプロパティが変更されたときに発生するイベントはありますか?あるいは、この問題に対処する別の方法がありますか? @Adolfoの助けを借りて

答えて

0

、これは動作します:

import Cocoa 
@NSApplicationMain 
class AppDelegate: NSObject, NSApplicationDelegate { 
    var panel: NSPanel! 

    func getPanelRect() -> NSRect { 
     let screenRect:CGRect = NSScreen.main()!.frame 
     return NSRect(
      x: screenRect.width/4, 
      y: screenRect.height/4, 
      width: screenRect.width/2, 
      height: screenRect.height/2 
     ) 
    } 

    func applicationDidFinishLaunching(_ aNotification: Notification) { 
     panel = NSPanel(
      contentRect: self.getPanelRect(), 
      styleMask: NSWindowStyleMask.nonactivatingPanel, 
      backing: NSBackingStoreType.buffered, 
      defer: false 
     ) 
     panel.alphaValue = 0.5 
     panel.backgroundColor = NSColor.red 
     panel.level = Int(CGWindowLevelForKey(CGWindowLevelKey.maximumWindow)) 
     panel.orderFront(nil) 

     NotificationCenter.default.addObserver(
      forName: NSNotification.Name.NSApplicationDidChangeScreenParameters, 
      object: NSApplication.shared(), 
      queue: OperationQueue.main 
     ) { notification -> Void in 
      print("screen parameters changed") 
      self.panel.setFrame(self.getPanelRect(), display: true) 
     } 
    } 
} 
関連する問題