Objective-Cで作成するコードとNSAlertがありますが、Swiftで作成したいと思います。
警告は、ユーザーがドキュメントを削除することを確認することです。
「削除」ボタンで削除機能を実行し、「キャンセル」ボタンで警告を消すだけです。
これをSwiftで書くにはどうすればよいですか?
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:@"Delete"];
[alert addButtonWithTitle:@"Cancel"];
[alert setMessageText:@"Delete the document?"];
[alert setInformativeText:@"Are you sure you would like to delete the document?"];
[alert setAlertStyle:NSWarningAlertStyle];
[alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
beginSheetModalForWindow:modalDelegate
は、OS X 10.10 Yosemiteでは非推奨です。
スイフト2
func dialogOKCancel(question: String, text: String) -> Bool {
let alert: NSAlert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.WarningAlertStyle
alert.addButtonWithTitle("OK")
alert.addButtonWithTitle("Cancel")
let res = alert.runModal()
if res == NSAlertFirstButtonReturn {
return true
}
return false
}
let answer = dialogOKCancel("Ok?", text: "Choose your answer.")
これは、ユーザーの選択に応じてtrue
またはfalse
を返します。
NSAlertFirstButtonReturn
は、ダイアログに追加された最初のボタン、ここでは「OK」ボタンを表します。
Swift
func dialogOKCancel(question: String, text: String) -> Bool {
let alert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.warning
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
return alert.runModal() == NSAlertFirstButtonReturn
}
let answer = dialogOKCancel(question: "Ok?", text: "Choose your answer.")
Swift 4
アラートのスタイルおよびボタン選択に列挙型を使用するようになりました。
func dialogOKCancel(question: String, text: String) -> Bool {
let alert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = .warning
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
return alert.runModal() == .alertFirstButtonReturn
}
let answer = dialogOKCancel(question: "Ok?", text: "Choose your answer.")
私はこれがあなたのために働くかもしれないと思う...
let a = NSAlert()
a.messageText = "Delete the document?"
a.informativeText = "Are you sure you would like to delete the document?"
a.addButtonWithTitle("Delete")
a.addButtonWithTitle("Cancel")
a.alertStyle = NSAlertStyle.WarningAlertStyle
a.beginSheetModalForWindow(self.view.window!, completionHandler: { (modalResponse) -> Void in
if modalResponse == NSAlertFirstButtonReturn {
print("Document deleted")
}
})
Swift 4:のJose Hidalgoの答えを更新しました。
let a: NSAlert = NSAlert()
a.messageText = "Delete the document?"
a.informativeText = "Are you sure you would like to delete the document?"
a.addButton(withTitle: "Delete")
a.addButton(withTitle: "Cancel")
a.alertStyle = NSAlert.Style.warning
a.beginSheetModal(for: self.window!, completionHandler: { (modalResponse: NSApplication.ModalResponse) -> Void in
if(modalResponse == NSApplication.ModalResponse.alertFirstButtonReturn){
print("Document deleted")
}
})