MacアプリでNSAlertを使ってアラートを表示する
Macアプリ で NSAlert をつかって、こういう↓アラートを表示します。
https://gyazo.com/5f2f424d75d18f1053249ce3e835b64e
code: Swift
let alert = NSAlert()
alert.alertStyle = .warning
alert.messageText = "削除しますか?"
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "キャンセル")
let response = alert.runModal()
switch response {
case .alertFirstButtonReturn:
print("OK")
case .alertSecondButtonReturn:
print("キャンセル")
default:
break
}
runModal でアラートを呼び出すと、戻り値が NSApplication.ModalResponse で返ってきます。
NSApplication.ModalResponse には OK や cancel もあるのですが、それは使えませんでした。
alertFirstButtonReturn や alertSecondButtonReturn で、 addButton( :) した順番に処理を分岐する必要があるようです。
Alert Text
https://gyazo.com/74327afd1e9a93670faf1c1a45bcfe31
Alertには messageText と infomativeText があります。
アップルのHuman Interface GuidelinesのAlert によると、messageTextが本文で、infomativeTextが補足という位置付けのようです。
code: Swift
alert.messageText = "Hogeエラー"
alert.informativeText = "Fugaを入力してください。"
設定するときは、それぞれのプロパティに文字列を代入します。
Alert Style
AlertにはStyle があります。
Styleを変更するときは、 alertStyle プロパティに NSAlert.Style を代入します。
NSAlert.Style は critical と informational と warning の3種類がありますが、 NSAlert.Style のリファレンスによると、 imfomational と warning は見た目の違いがないそうです。
Currently, there is no visual difference between informational and warning alerts. You should only use the critical (or “caution”) alert style if warranted, as specified in the “Alerts” chapter in macOS Human Interface Guidelines.
というわけで、 通常のアラートは informational か warning 、特別なアラートは critical という使い分けをします。
https://gyazo.com/4153da97ffcf466de4ae66c40690e73a
こちら↑が informational と warning のアラート。
https://gyazo.com/27bb098ea2842c83bf4155d99f4a19b8
こちら↑がcritical のアラートです。
ボタンの変更
ボタンの文字(上の画像の OK )を変更する場合は、つぎのように addButton(: ) をつかいます。
code: Swift
alert.addButton(withTitle: "OKですよ")
とすると
https://gyazo.com/4ede0d2f8bf3d6fc189758472346689c
このようにボタンのタイトルが変わります。
ボタンクリックの取得
runModal() の戻り値 NSApplication.ModalResponse で、ボタンをクリックした結果を取得することができます。
code: Swift
let response = alert.runModal()
ModalResponse には、OK や cancel などがあるので、つぎのように switch をつかって処理を分岐することができます。。
code: Swift
let response = alert.runModal()
switch response {
case .OK:
print("OK")
case .alertFirstButtonReturn:
print("first")
case .alertSecondButtonReturn:
print("first")
case .alertThirdButtonReturn:
print("first")
case .abort:
print("abort")
case .cancel:
print("cancel")
case .continue:
print("continue")
case .stop:
print("stop")
default:
print("default")
}
テストしてみたところ、標準のOKボタンの場合は cancel が返ってきました(なぜOKでないのか謎です)。
alert.addButton(withTitle: "OKですよ") のように、自分で addButton(: ) したときは、alertFirstButtonReturn が返ってきました。
OK や abort などがどういうタイミングで返ってくるのかは、謎のままです(情報お待ちしております)。