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

1      

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.

1      

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) { NotificationCenter.default.post(name: 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") }

1      

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 {
            print(w.frame.origin)
        }
    }

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

1      

Thank you!

1      

Hacking with Swift is sponsored by MadMachine

SPONSORED Want to try Swift on microcontrollers? MadMachine provides ways to interact with the physical world in a Swift way. Join us and have fun!

Get it now

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.