Storyboardを使わずにMacOSアプリを作ってHello Worldする方法

検索しても意外と出てこない。みなさん本当にStoryboardを使っていらっしゃるのでしょうか。それとも検索の仕方が悪いのでしょうか。

はじめに

作業環境はこんな感じ - macOS 10.14.3 Mojave - XCode 10.1 - Swift 4

プロジェクトの準備

プロジェクトを新規作成する。このときに Storyboard を使わないように設定する。そうすると AppDelegate.swift というファイルが作成される。

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!


    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }


}

ソースコードの編集

applicationDidFinishLaunching の中をこんな風に書き換えます。

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        window.title = "Hello World"
        let windowWidth = window.frame.width
        let windowHeight = window.frame.height
        
        let helloLabel = NSTextField()
        helloLabel.stringValue = window.title
        helloLabel.sizeToFit()  // Resizes the receiver to fit its text.
        let x = windowWidth/2 - helloLabel.bounds.width / 2
        helloLabel.setFrameOrigin(NSPoint(x:x, y:windowHeight/2))
        
        let view = NSView(frame: NSRect(x:0, y:0, width:windowWidth, height:windowHeight))
        view.addSubview(helloLabel)
        window.contentView?.addSubview(view)
    }

やっていることは - なんとなくウィンドウのタイトルも Hello World にしてみる - あとで使うためにウィンドウ幅と高さを保存 - NSTextField を作る - 文字列を Hello World に設定(ウィンドウタイトルと同じにする) - NSTextFieldの大きさを文字列がおさまるようにリサイズ - frameの起点位置を調整して文字列が画面の真ん中に来るようにする - NSViewを作ってHello World文字列を追加 - WindowのViewに今作ったViewを追加 という感じ。表示したいだけならNSViewを経由しなくても良い。

frame というのは下の参考資料のリンクによると、「frameの四角形は、superview上における位置とサイズです」ということです。superviewというのは親Viewですね。

参考資料

developer.apple.com

そもそもViewってなんなの?という疑問に答えるページ。Viewとは階層構造になっていて、という解説があります。 developer.apple.com

そもそもAppleはどんなNSViewを準備しているの?という疑問に答えるページ。 developer.apple.com