iPhoneアプリ アラートを表示する方法

投稿者: | 2017年2月26日

UIAlertControllerでアラート(メッセージダイアログ)を表示する方法です

Xcode 8 と Swift 3を使います

以下のコードを記述します

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// UIAlertControllerクラスのインスタンスを生成
let alert: UIAlertController =
    UIAlertController(title: "タイトル",
                      message: "メッセージ",
                      preferredStyle:  UIAlertControllerStyle.alert)
 
// Actionの設定
let defaultAction: UIAlertAction =
    UIAlertAction(title: "OK", style: UIAlertActionStyle.default,
    handler:{
    // OKボタンが押された時の処理
    (action: UIAlertAction!) -> Void in
    print("OK")
})
let cancelAction: UIAlertAction =
    UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel,
    handler:{
    // Cancelボタンが押された時の処理
    (action: UIAlertAction!) -> Void in
    print("Cancel")
})
 
// UIAlertControllerにActionを追加
alert.addAction(cancelAction)
alert.addAction(defaultAction)
 
// Alertを表示
present(alert, animated: true, completion: nil)

実行結果です