2

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

Community
  • 1
  • 1
Francesco
  • 521
  • 1
  • 6
  • 14

2 Answers2

11

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)
    }
}
Hamer
  • 1,354
  • 1
  • 21
  • 34
  • Please note that this is 'viewDidAppear' not viewDidLoad, which gets called _before_ the WindowController's windowDidLoad and thus does not work. (I have no idea why it never occurred to me to make the viewController the Window's delegate. This simplifies matters.) – green_knight Sep 23 '19 at 12:39
9

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
    }
}
Miknash
  • 7,888
  • 3
  • 34
  • 46
Michael
  • 8,891
  • 3
  • 29
  • 42