How to get resolution change event in swift?

前端 未结 3 397
臣服心动
臣服心动 2021-01-21 12:09

I try to make an app, and now i shoud make some changes when screen resolution will change, but i coudn\'t find how to intercept this event.

Do you have any ideea ho

相关标签:
3条回答
  • 2021-01-21 12:41

    Swift 4:

    The didChangeScreenParametersNotification is posted when the configuration of the displays attached to the computer is changed.

    Inside the func applicationDidFinishLaunching() in AppDelegate class or func viewDidLoad() in ViewController class, insert the following code:

    NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification,
                                           object: NSApplication.shared,
                                           queue: OperationQueue.main) {
                                           notification -> Void in
                                           print("screen parameters changed")}
    

    I personally, used it to center the position of my application when switching between the Mac and the external screen.

    0 讨论(0)
  • 2021-01-21 12:44

    Here is the updated Swift 3 code:

     NotificationCenter.default.addObserver(forName: NSNotification.Name.NSApplicationDidChangeScreenParameters,
                                                                object: NSApplication.shared(),
                                                                queue: OperationQueue.main) {
                                                                    notification -> Void in
                                                                    print("screen parameters changed")
        }
    
    0 讨论(0)
  • 2021-01-21 12:51

    The NSApplicationDidChangeScreenParametersNotification is posted when the configuration of the displays attached to the computer is changed, so you can register for that notification, e.g. with

    NSNotificationCenter.defaultCenter().addObserverForName(NSApplicationDidChangeScreenParametersNotification,
        object: NSApplication.sharedApplication(),
        queue: NSOperationQueue.mainQueue()) {
            notification -> Void in
            println("screen parameters changed")
    }
    

    Note that there can be various reasons why this notification is fired, e.g. a change in the dock size (as observed in Cocoa Dock fires NSApplicationDidChangeScreenParametersNotification), so you have to "remember" the old resolution and compare it with the new resolution.

    0 讨论(0)
提交回复
热议问题