1つのプロジェクトの中の複数の箇所でアラートを表示していたので、
アラートの表示処理を少し楽にするためにUIAlertControllerを拡張しました。
コード
import UIKit
extension UIAlertController {
class func singleBtnAlertWithTitle(title: String, message: String, completion: (() -> Void)?) -> UIAlertController
{
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {
(action:UIAlertAction!) -> Void in
if let completion = completion {
completion()
}
}))
return alert
}
class func doubleBtnAlertWithTitle(title: String, message: String, otherBtnTitle:String, completion: (() -> Void)?) -> UIAlertController
{
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: otherButtonTitle, style: .Default, handler: {
(action:UIAlertAction!) -> Void in
if let completion = completion {
completion()
}
}))
return alert
}
OKボタンしか存在しないアラートを使用したい場合はこんなかんじ。
let alert = UIAlertController.singleBtnAlertWithTitle("title", message: "message", completion: nil)
self.presentViewController(alert, animated: true, completion: nil)
ボタンが2つあって、一つはOKボタン(.Cancel)、もう一つは何か処理を行うアラートを使用したい場合はこんなかんじ。
let alert = UIAlertController.doubleBtnAlertWithTitle("title", message: "message", otherBtnTitle: "view表示", completion: {
let vc = UIViewController()
let nav = UINavigationController(rootViewController: vc)
self.presentViewController(nav, animated: true, completion: nil)
})
self.presentViewController(alert, animated: true, completion: nil)