MacOS 开发(九):NSViewController + NSPanel 弹窗

1,407 阅读1分钟

一、需求来源

所有直接复用控制器的方法都是异常的强大、必须掌握的技能。 1、首先创造一个控制器 NSViewController 实例。

2、基于控制器创建 NSWindow,配置属性。

3、然后将控制器赋值给 Window的 contentViewController属性。

ezgif.com-video-to-gif.gif

二、使用示例

🌰🌰:
    //弹出NSViewController
    func showSheetController() {
        let controller = NNBatchClassCreateController()
        let rect = CGRectMake(0, 0, kScreenWidth*0.25, kScreenHeight*0.25)

        NSWindow.show(with: controller, size: rect.size) { (response) in
            DDLog(response)
        }
    }

  //NSViewController 中关闭弹窗:
  NSWindow.end(with: self, response: NSApplication.ModalResponse.OK)

三、源码

@objc public extension NSWindow {
    /// 默认大小
    static var defaultRect: CGRect {
        return CGRectMake(0, 0, kScreenWidth*0.4, kScreenHeight*0.5)
    }

    static func create(_ rect: CGRect = NSWindow.defaultRect, title: String = NSApplication.appName) -> Self {
    //        let style = NSWindow.StyleMask.titled.rawValue | NSWindow.StyleMask.closable.rawValue | NSWindow.StyleMask.miniaturizable.rawValue | NSWindow.StyleMask.resizable.rawValue
        let style: NSWindow.StyleMask = [.titled, .closable, .miniaturizable, .resizable]
        let window = self.init(contentRect: rect, styleMask: style, backing: .buffered, defer: false)
        window.title = title
        window.titlebarAppearsTransparent = true
        return window;
    }

    static func create(_ rect: CGRect = NSWindow.defaultRect, controller: NSViewController) -> Self {
        let window = Self.create(rect, title: controller.title ?? "")
        window.contentViewController = controller;
        return window;
    }
    
    static func createMain(_ rect: CGRect = NSWindow.defaultRect, title: String = NSApplication.appName) -> Self {
        let window = Self.create(rect, title: title)
        window.contentMinSize = window.frame.size;
        window.makeKeyAndOrderFront(self)
        window.center()
        return window;
    }
    /// 下拉弹窗
    static func show(with controller: NSViewController, size: CGSize, handler: ((NSApplication.ModalResponse) -> Void)? = nil) {
        controller.preferredContentSize = size
        let rect = CGRectMake(0, 0, size.width, size.height)

        let panel = Self.create(rect, controller: controller)
        NSApp.mainWindow?.beginSheet(panel, completionHandler: handler)
    }
    /// 下拉弹窗关闭
    static func end(with controller: NSViewController, response: NSApplication.ModalResponse) {
        guard let window = controller.view.window else { return }
        if window.isMember(of: Self.classForCoder()) == true {
//            view.window?.orderOut(self)
            NSApp.mainWindow?.endSheet(window, returnCode: response)
        }
    }
}