Swift2でUIAlertControllerをどこからでも呼び出せるようにする

いい記事が見当たらなかった
どこからでも呼び出せるようにして、ボタンをおした時の挙動は呼び出し側で定義するできるようにしてみる




アラート表示用の汎用クラス



以下をコピペ

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/** アラート表示クラス */
class Alert: NSObject {
 
     
    /** 確認メッセージを表示する */
    static func show(
        title title: String,
        withMsg msg:String ) {
             
            // UIAlertControllerクラスのインスタンスを生成
            // タイトル, メッセージ, Alertのスタイルを指定する
            // 第3引数のpreferredStyleでアラートの表示スタイルを指定する
            let alert: UIAlertController = UIAlertController(title: title, message: msg, preferredStyle:  UIAlertControllerStyle.Alert)
             
             
            // Alertを表示 最全面のViewControllerの取得
            var tc = UIApplication.sharedApplication().keyWindow?.rootViewController;
            while ((tc!.presentedViewController) != nil) {
                tc = tc!.presentedViewController;
            }
            tc.presentViewController(alert, animated: true, completion: nil)
    }
     
    /**
     キャンセル・OKを持つシンプルなアラート
     ```
     // 使用例
     let ok :Void -> Void = {
        print("OK")
     }
     Alert.show(
        title: "title",
        withMsg: "msg",
        okAction: ok,
        cancalAction: { print("cancel") })
    ```
     */
    static func show(
        title title: String,
        withMsg msg:String,
        okAction ok:Void -> Void,
        cancalAction cancel:Void -> Void) {
         
        // タイトル, メッセージ, Alertのスタイル
        let alert: UIAlertController = UIAlertController(title: title, message: msg, preferredStyle:  UIAlertControllerStyle.Alert)
         
        // OKボタン
        let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{
            (action: UIAlertAction!) -> Void in
            ok()
        })
        // キャンセルボタン
        let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertActionStyle.Cancel, handler:{
            (action: UIAlertAction!) -> Void in
            cancel()
        })
         
        alert.addAction(cancelAction)
        alert.addAction(defaultAction)
         
         
        // Alert表示 最全面のViewControllerの取得
        var tc = UIApplication.sharedApplication().keyWindow?.rootViewController;
        while ((tc!.presentedViewController) != nil) {
            tc = tc!.presentedViewController;
        }
        tc.presentViewController(alert, animated: true, completion: nil)
    }
     
}



アラート表示用の汎用クラスの使用方法


使用方法はドキュメントコメントを見れば問題ないはず
キャンセルなど特になにもしない場合は {} を渡す

1
2
3
4
5
6
7
8
let ok :Void -> Void = {
    print("OK")
}
Alert.show(
    title: "title",
    withMsg: "msg",
    okAction: ok,
    cancalAction: {})


2016年8月20日土曜日