エラー表示やユーザーに確認を求める時など、アプリ内で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")
})