TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.