调整窗口大小事件

Fra*_*sco -1 cocoa swift

我正在创建一个简单的操作系统应用程序,但我找不到任何地方如何进行调整大小事件.

让我们假设我想要打印新的宽度和高度,我有这个控制器:

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

}
Run Code Online (Sandbox Code Playgroud)

我需要添加什么?谢谢.

我的问题与Swift/Objective-C中的Listen for window resize事件不同.因为我的视图必须扩展NSViewController而不是NSWindowController.在他的回答中,他没有解释究竟windowWillResize要返回什么

Ham*_*mer 8

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)
    }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 7

您需要在NSWindowDelegate某处实现,并将窗口的委托设置为该对象.如果需要,可以在视图控制器中实现此代码.

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
    }
}
Run Code Online (Sandbox Code Playgroud)