Swiftで単純なアラート制御(UIAlertControllerの実装)


はじめに

勇んで書き残した前のTips【iOS8非推奨】Swiftで単純なアラート制御(UIAlertViewDelegateの実装)はiOS8非推奨だったというわけで、 iOS8推奨 のアラートを書きます。

OK・キャンセル

ViewController.swift
import UIKit

class ViewController: UIViewController {

    var alertType: Int!;

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func tapButton(sender: UIButton) {
        var alert = UIAlertController(title: "iOS8のアラート!", message: "OK/Cancel?", preferredStyle: .Alert)

        let okAction = UIAlertAction(title: "OK", style: .Default) {
            action in NSLog("OK!")
        }

        let cancelAction = UIAlertAction(title: "いいえ", style: .Cancel) {
            action in NSLog("Cancel!")
        }

        alert.addAction(okAction)
        alert.addAction(cancelAction)

        presentViewController(alert, animated: true, completion: nil)
    }
}

ラーメン・寿司・おあずけ

import UIKit

class ViewController: UIViewController {

    var alertType: Int!;

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func tapButton(sender: UIButton) {
        var alert = UIAlertController(title: "iOS8のアラート!", message: "?/?/?", preferredStyle: .Alert)

        alert.addAction(UIAlertAction(title: "ラーメン ?", style: .Default) {
            action in NSLog("?!")
            })

        alert.addAction( UIAlertAction(title: "寿司 ?", style: .Destructive) {
            action in NSLog("?!")
        })

        alert.addAction( UIAlertAction(title: "おあずけ ?", style: .Cancel) {
            action in NSLog("?!")
        })

        presentViewController(alert, animated: true, completion: nil)
    }
}

実行結果

要点

  1. デリゲートからクロージャに変更となり、処理が散らばらない!
  2. UIAlertActionが選択項目1つと結びついてるので読みやすい。直しやすい。
  3. 一時変数をつくらず、alert.addAction(UIAlertAction(title: "OK", style: .Default) { action in NSLog("OK!") })できて嬉しい。
  4. コード量も減ってステキ
  5. .Destructive指定すると、寿司の文字が赤くなり、鮪とマッチしてよい

ここより参考になるリンク

まとめ

寿司食いたい。