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

投稿者: | 2017年2月26日

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

Xcode 8 と Swift 3を使います

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


        // 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)

実行結果です