LoginSignup
23
25

More than 5 years have passed since last update.

AlertViewControllerをどこからでも呼べるようにラップしてみる

Last updated at Posted at 2015-09-23

エラー表示やユーザーに確認を求める時など、アプリ内でAlertを表示する場面は多いかと思います。

つど、ViewControllerなどにAlertを表示するコードを何度も書くのも嫌なので、
AlertViewControllerを拡張して、基本的なAlertであればどこからでも簡単に表示できるようにしてみました。

ボタンを押した際のコールバックも取れるようになっています。

ついでに最前面のViewControllerを取得するためにUIViewControllerも拡張しています。

以下、コード。

UIAlertViewControllerの拡張

import UIKit

extension UIAlertController {

    class func oneButton(title: String, message: String, btnOk: String = "OK", handler: ((UIAlertAction!) -> Void)?) {
        let alert = self.init(title: title, message: message, preferredStyle: .Alert)
        let okAction = UIAlertAction(title: btnOk, style: .Default, handler: handler)

        alert.addAction(okAction)

        let viewController = UIViewController.getFrontViewController()
        viewController.presentViewController(alert, animated: true, completion: nil)
    }

    class func twoButton(title: String, message: String, btnOk: String = "OK", btnNo: String = "NO", handlerOk: ((UIAlertAction!) -> Void)?, handlerNo: ((UIAlertAction!) -> Void)?) {
        let alert = self.init(title: title, message: message, preferredStyle: .Alert)
        let okAction = UIAlertAction(title: btnOk, style: .Default, handler: handlerOk)
        let noAction = UIAlertAction(title: btnNo, style: .Cancel, handler: handlerNo)

        alert.addAction(okAction)
        alert.addAction(noAction)

        let viewController = UIViewController.getFrontViewController()
        viewController.presentViewController(alert, animated: true, completion: nil)
    }

}

UIViewControllerの拡張


import UIKit

extension UIViewController {

    //最前面のViewController取得
    class func getFrontViewController() -> UIViewController {
        var viewController = UIApplication.sharedApplication().keyWindow?.rootViewController
        while let vc = viewController?.presentedViewController {
            if !(vc is UINavigationController) {
                viewController = vc
            }
        }

        return viewController!
    }
}

使用例:

        //1ボタン
        UIAlertController.oneButton("title", message: "message", btnOk: "OK", handler: { (alert) in
            print("onBtnOk")
        })
       
     //2ボタン
        UIAlertController.twoButton("title", message: "message", btnOk: "Ok", btnNo: "No", handlerOk: { (alert) in
            print("onBtnOk")
        }, handlerNo: { (alert) in
            print("onBtnNo")
        })
23
25
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
23
25