xibファイルを読み込んでNSWindowContrllerを表示する


概要

  • xibファイルを読み込んで別ウィンドウを表示したい。

  • Storyboardから、NSWindowController(with xibファイル)を表示する

参考

実装

  • NSWindowControllerのクラスを定義する。(このときxibファイルも一緒に作成する)
SampleWindowController.swift
import Cocoa


class SampleWindowController: NSWindowController {

    // MARK: - Properties

    let windowTitle: String
    let message: String

    @IBOutlet weak var messageLabel: NSTextField!

    // MARK: - Lifecycle

    init(withTitle title: String, message: String, window: NSWindow?) {
        self.windowTitle = title
        self.message = message
        super.init(window: window)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func windowDidLoad() {
        super.windowDidLoad()
        configureUI()
    }

    override var windowNibName: NSNib.Name? {
        return String(describing: type(of: self))
    }

    // MARK: - Helpers

    private func configureUI() {
        window?.title = windowTitle
        messageLabel.stringValue = message
    }
}
  • クラスとxibの結びつけは下記のコード。これが今回のポイント。
SampleWindowController.swift
override var windowNibName: NSNib.Name? {
        return String(describing: type(of: self))
}
  • ViewControllerからの呼び出し方は以下の通り。
ViewController.swift
var sampleWindowController: SampleWindowController?

// (中略)

@IBAction func openingWindowButtonClicked(_ sender: Any) {
    let sampleWindowController = SampleWindowController(withTitle: "Title of SampleWindowController",
                                                        message: "passed message for SampleWindowController..",
                                                        window: nil)
    sampleWindowController.showWindow(self)
    self.sampleWindowController = sampleWindowController
}