FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

Detect the position of a window

Forums > macOS

Swift, Storyboards

Is it possible to detect if the user has change the position of a window?

I know how to get the position of the window in the viewDidLoad for instance. But I do not know how to know if the position has changed.

let position = self.view.window!.frame.origin


You can listen for various notifications such as didMoveNotification, didResizeNotification and didMiniaturizeNotification. See the NSWindow documentation for a complete list.

If your window has a delegate, you can implement one of the delegate methods to receive those notifications.


Thank you. I know how to do a regular notification when for instance the user clicks a button, but I do not how to apply it here when the user changes the position of a window.

// 1-send the notification:
@IBAction func changePosition(_ sender: UIButton) { NSNotification.Name("notification1"), object: nil) }

// 2-viewDidLoad of the receiving page:
NotificationCenter.default.addObserver(self, selector: #selector(notificacio1Action), name: NSNotification.Name("notification1"), object: nil)

// 3-Outside viewDidLoad
@objc func notificacio1Action() { print("notification recived") }


You need to implement the NSWindowDelegate functions that listen for the notifications you are interested in. The system will send out those notifications at the appropriate times.

For instance, in your ViewController's viewDidAppear, method, you can wire it up as the delegate:

    override func viewDidAppear() {
        self.view.window?.delegate = self

and then add NSWindowDelegate conformance in an extension:

extension ViewController: NSWindowDelegate {
    func windowDidMove(_ notification: Notification) {
        if let w = notification.object as? NSWindow {

    func windowDidResize(_ notification: Notification) {
        if let w = notification.object as? NSWindow {


Thank you!


Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.