Francesco
Francesco

Reputation: 531

Resize windows Event

I'm creating a simple OS app but I cannot find anywhere how to take the resize event.

Let's assume that I wanna print the new width and height and I have this controller:

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override var representedObject: AnyObject? {
        didSet {
            // Update the view, if already loaded.
        }
    }

}

What i have to add? Thank you.

My question is not the same as Listen for window resize event in Swift / Objective-C. Since my View have to extend NSViewController and not NSWindowController. This in his answer he did not explain what windowWillResize has to return exactly

Upvotes: 2

Views: 6261

Answers (2)

Hamer
Hamer

Reputation: 1383

Swift 4 - macOS 10.13

class ViewController: NSViewController, NSWindowDelegate {

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

    func windowDidResize(_ notification: Notification) {
        // This will print the window's size each time it is resized.
        print(view.window?.frame.size)
    }
}

Upvotes: 11

Michael
Michael

Reputation: 9044

You need to implement NSWindowDelegate somewhere, and set the window's delegate to that object. If you want, you could implement this code in your view controller.

class ViewController: NSViewController, NSWindowDelegate {
    override func viewWillAppear() {
        self.view.window.delegate = self
    }

    func windowWillResize(sender: NSWindow, toSize frameSize: NSSize) -> NSSize {
        // Your code goes here
    }

    func windowDidResize(notification: NSNotification) {
        // Your code goes here
    }
}

Upvotes: 9

Related Questions