NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.