windowDidResize 协议 swift OSX

windowDidResize protocol swift OSX

我正在创建一个程序,我希望 UI 根据 window 的大小进行更改。我正在寻找一些在 window 调整大小时调用的方法。我查看了 windowDidResize 的文档,但是当 window 调整大小时我无法让它工作。

import SpriteKit
import AppKit
class GameScene: SKScene , SKPhysicsContactDelegate ,NSWindowDelegate{

****   bunch of code   ****


  func windowDidResize (notification: NSNotification) {
    HUDComp.updatePosition(size)
    println("Screen has been resized")
  }
}

任何信息将不胜感激。

如果你继承了NSWindowDelegate,你唯一要做的就是在NSNotificationCenter上添加观察者。 代码在这里。

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("windowDidResize:"), name: NSWindowDidResizeNotification, object: nil)

我的两分钱 swift 5.(同时显示委托和通知,选择一个..)

  import Cocoa

class ViewController: BaseController, NSWindowDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.makeItListenZoom()
    }



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

    }


    private final func makeItListenZoom(){
        NotificationCenter.default.addObserver(forName: NSWindow.didResizeNotification, object: nil, queue: OperationQueue.main) { (n: Notification) in

            print("didresize---")
        }
    }



    func windowDidResize(_ notification: Notification){
           print("windowDidResize")
       }
}

Swift 5 macOS 11+

针对 Xcode 12.2 和 macOS Big Sur 进行了更新。

这将在 window 的尺寸发生变化时调用 windowDidResize

class ViewController: NSViewController, NSWindowDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(NSWindowDelegate.windowDidResize(_:)), name: NSWindow.didResizeNotification, object: nil)
    }

    func windowDidResize(_ notification: Notification) {
        print(view.window?.frame.size as Any)
    }
}