LoginSignup
1
1

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-08-28

概要

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

-w809

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

-w1156

参考

実装

  • 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
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1