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
}
Alert Text
https://gyazo.com/74327afd1e9a93670faf1c1a45bcfe31
code: Swift
alert.messageText = "Hogeエラー"
alert.informativeText = "Fugaを入力してください。"
設定するときは、それぞれのプロパティに文字列を代入します。
Alert Style
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 のアラートです。
ボタンの変更
code: Swift
alert.addButton(withTitle: "OKですよ")
とすると
https://gyazo.com/4ede0d2f8bf3d6fc189758472346689c
このようにボタンのタイトルが変わります。
ボタンクリックの取得
code: Swift
let response = alert.runModal()
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 などがどういうタイミングで返ってくるのかは、謎のままです(情報お待ちしております)。