UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on 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

4      

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.

4      

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") }

4      

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)
        }
    }
}

4      

Thank you!

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot 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.