【Swift3】【UIAlertController】アラートを出す。

アラートを出します。

参考はこちら。
【Swift】アラートを表示する(Alert/ActionSheet) – Qiita
【swift】アラート(Alert) / アクションシート(ActionSheet) – 父ロボの開発覚書
Swift:UIAlertController でアラートを表示するサンプルコード | siro:chro

Swift3になって色々直された。
んでこんな感じ。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    @IBAction func alartButton(sender: AnyObject) {
        alertHyouji()
    }
    
    func alertHyouji()  {
        
        //アラートのインスタンス作成、タイトル、メッセージ、スタイル。
        let alert: UIAlertController = UIAlertController(title: "Alert",
                                                         message: "Count clears.",
                                                         preferredStyle:  UIAlertControllerStyle.actionSheet)

        // OKボタン
        let defaultAction: UIAlertAction = UIAlertAction(title: "OK",
                                                         style: UIAlertActionStyle.default,
                                                         handler:{(action: UIAlertAction!) -> Void in
                                                            //ココに処理を書く
                                                            print("OK")
        })
        
        // Destructive 赤文字ボタン
        let destructiveAction: UIAlertAction = UIAlertAction(title: "赤いよ",
                                                             style: UIAlertActionStyle.destructive,
                                                             handler:{
                                                                (action:UIAlertAction!) -> Void in
                                                                //ココに処理を書く
                                                                print("Destructive")
        })
        
        // Cancelボタン 一つだけしか指定できない
        let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel",
                                                        style: UIAlertActionStyle.cancel,
                                                        handler:{
                                                            (action:UIAlertAction!) -> Void in
                                                            print("Cancel")
        })
        
        // AddAction 記述順に反映される。Cancelは最下段固定。
        alert.addAction(defaultAction)
        alert.addAction(destructiveAction)
        alert.addAction(cancelAction)
        
        // alartを表示する。
        present(alert, animated: true, completion: nil)
    }
}

UIAlertControllerStyle.Alert // アラート
UIAlertControllerStyle.ActionSheet // アクションシート
の2つのスタイルがあります。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です