LoginSignup
14
12

More than 5 years have passed since last update.

UIAlertControllerを拡張してアラート表示をちょっと便利にした

Posted at

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)
14
12
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
14
12