Table of Contents
macOS向けのアプリケーションウィンドウを終了させる際に確認ダイアログを表示するプログラムのサンプルです。
プロジェクト新規作成後の AppDelegate.swift を以下のように変更して下さい。
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
window.delegate = self
}
func applicationWillTerminate(_ aNotification: Notification) {
}
// 確認ダイアログの作成と表示
func showDialog(_ mainText: String, description: String) -> Bool {
let alert = NSAlert()
alert.messageText = mainText
alert.informativeText = description
alert.alertStyle = .warning
alert.addButton(withTitle: "はい")
alert.addButton(withTitle: "いいえ")
return alert.runModal() == .alertFirstButtonReturn
}
func windowWillClose(_ notification: Notification) {
// ウィンドウを閉じると同時にアプリケーションを終了
NSApp.terminate(window)
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
// 閉じる前に確認ダイアログを表示
return showDialog("アプリを終了しますか?", description: "保存されていない編集は破棄されます。")
}
}
サンプルの解説
NSWindowDelegateの設定
ウィンドウ(NSWindow)が閉じられようとしていることを感知するには、そのウィンドウの delegate に NSWindowDelegate を指定します。上記のサンプルでは AppDelegate に NSWindowDelegate を設定し、これをウィンドウに渡しています。
window.delegate = self
これによって、ウィンドウが閉じられる前にメソッド windowShouldClose が呼び出されるようになります。ここで、ダイアログを表示するコードを書きます。
ダイアログの作成と表示
ダイアログの作成はクラス NSAlert を利用します。ダイアログのタイプや表示するテキスト、選択肢を指定します。
// 確認ダイアログの作成と表示
func showDialog(_ mainText: String, description: String) -> Bool {
let alert = NSAlert()
alert.messageText = mainText
alert.informativeText = description
alert.alertStyle = .warning
alert.addButton(withTitle: "はい")
alert.addButton(withTitle: "いいえ")
return alert.runModal() == .alertFirstButtonReturn
}
これで「はい」を押すと true が、「いいえ」を押すと false が返される警告ダイアログができます。このダイアログから true が返された場合にウィンドウが閉じられます。
ウィンドウを閉じるとともにアプリを終了させる
デフォルトではウィンドウを閉じてもアプリ自体は終了しませんが、ここでは NSWindowDelegate の windowWillClose を使ってウィンドウを閉じると同時にアプリケーションを終了するようにしています。
以上、NSWindow を閉じる前に NSAlert で確認ダイアログを表示するプログラムのサンプルでした。

