LoginSignup
6
12

More than 5 years have passed since last update.

Swift3.0におけるアラート制御

Last updated at Posted at 2017-03-31

iOS 7まではUIAlertViewを利用してアラート制御をしていたのですが,iOS 8からはUIAlertControllerを利用してアラート制御することが推奨されています。

UIAlertControllerを使ってどのようにアラート制御するのか整理しました。

開発環境


Xcode Ver 8.2.1-
Swift 3.0
iOS 10.2
iPhone 7 Plus Simulator

UIAlertController実装の手順

実装の手順をコードだけでなく,図でも表しましたので参考にして下さい。
処理手順の画像

1.UIAlertControllerの作成

アラートを構成するボタンやテキストボックスを入れる入れ物を構築します。UIAlertControllerを作成するコードは以下です。

let コントローラー名 = UIAlertController(title: "アラートのタイトル",message: "アラートの説明", preferredStyle: UIAlertControllerStyle.alert)

2.アラートの部品の作成

アラートを構成する部品を作成します。主に,OKボタンやCANCELボタン,テキストボックスなどです。また,自分オリジナルの部品を作成することもできます。部品を作成するコードは以下です。

let 部品名 = UIAlertAction(title: "部品名", style:UIAlertActionStyle.default){
(action: UIAlertAction) in
// 以下はボタンがクリックされた時の処理
            print("Hello")
}

この時,UIAlertAction.defaultの.defaultを.cancelなどに変えることで,キャンセルボタンを実装できます。

3.部品をUIAlertControllerに追加

1で作成した入れ物(コントローラー)に部品を追加していきます。追加するコードは以下です。

コントローラー名.addAction(部品名)

4.アプリにアラートを表示させる

最後は今まで作成した入れ物(コントローラー)をアプリに表示させる動作です。

present(コントローラー名,animated: true, completion: nil)

サンプルコード

ViewController.swift
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 tapAlertButton(_ sender: Any) {
//        ① コントローラーの実装
        let alertController = UIAlertController(title: "test",message: "アラートボタン", preferredStyle: UIAlertControllerStyle.alert)

//        ②-1 OKボタンの実装
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){ (action: UIAlertAction) in
//        ②-2 OKがクリックされた時の処理
            print("Hello")
        }
//        CANCELボタンの実装
        let cancelButton = UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.cancel, handler: nil)

//        ③-1 ボタンに追加
        alertController.addAction(okAction)
//        ③-2 CANCELボタンの追加
        alertController.addAction(cancelButton)

//        ④ アラートの表示
        present(alertController,animated: true,completion: nil)
    }
}

実行結果

実行結果は以下のようになります。

Simulator Screen Shot 2017.03.31 20.09.41.png

以上,Swift3.0でアラートを制御する方法でした。

6
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
12