Search code examples
swiftmacoscocoa

Perform function at the end of windodDidResize event


I would like to perform a function after the windowDidResize event ended. While this block is running, it prints the following:

NotificationCenter.default
  .publisher(for: NotificationName.windowDidResize)
  .sink { _ in

      // Perform something
      print("WindowDidResize")

   }.store(in: &cancellableBag)

Print output:

WindowDidResize
WindowDidResize
WindowDidResize
WindowDidResize <-- Want to run a function here

How can I perform a function after the last windowDidResize only once? I'd like to hide some UI elements while the window is being resize (because it make operation sooo slow) and redraw them after the window was resized (with delay of 0.25 sec or something else).

Swift 5.3 | Xcode 12.2 | macOS 11.1


Solution

  • You can implement the optional method windowDidEndLiveResize which will be called only once at the end of the window resizing:

    You can also monitor didendliveresizenotification

    import Cocoa
    
    class ViewController: NSViewController, NSWindowDelegate {
        override func viewDidLoad() {
            super.viewDidLoad()
        }
        override func viewWillAppear() {
            super.viewWillAppear()
            view.window?.delegate = self
        }
        func windowDidEndLiveResize(_ notification: Notification) {
            print(#function)
        }
    }