LoginSignup
14

More than 3 years have passed since last update.

使いやすいUIAlertControllerのExtensionを考えたので載せてみる

Last updated at Posted at 2019-05-06

実装

extension UIAlertController {
    static func noButtonAlert(title: String?, message: String?) -> UIAlertController {
        return UIAlertController(title: title, message: message, preferredStyle: .alert)
    }
    static func okAlert(title: String?,
                        message: String?,
                        okHandler: ((UIAlertAction) -> Void)? = nil) -> UIAlertController {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(.init(title: "OK", style: .default, handler: okHandler))
        return alert
    }

    static func errorAlert(title: String? = "⚠️",
                           error: Error,
                           okHandler: ((UIAlertAction) -> Void)? = nil) -> UIAlertController {
        let alert = UIAlertController(title: title, message: "\(error)", preferredStyle: .alert)
        alert.addAction(.init(title: "OK", style: .default, handler: okHandler))
        return alert
    }

    static func fieldAlert(title: String?,
                           message: String?,
                           placeholder: String?,
                           handler: ((String?) -> Void)? = nil) -> UIAlertController {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addTextField {
            $0.placeholder = placeholder
        }
        alert.addAction(.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in
            handler?(alert.textFields?.first?.text)
        }))
        alert.addAction(.init(title: "Cancel", style: .cancel, handler: { (action) in
            handler?(nil)
        }))
        return alert
    }
}

extension UIViewController {
    func present(_ alert: UIAlertController, completion: (() -> Void)? = nil) {
        present(alert, animated: true, completion: completion)
    }

    func present(_ alert: UIAlertController, _ autoDismissInterval: TimeInterval, completion: (() -> Void)? = nil) {
        present(alert, animated: true, completion: { [weak self] in
            DispatchQueue.main.asyncAfter(deadline: .now() + autoDismissInterval) {
                self?.dismiss(animated: true, completion: completion)
            }
        })
    }
}

使い方

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // OKボタンのみのAlertを表示
        present(.okAlert(title: nil, message: "グループを作成しました"))

        // OKボタンのついたErrorを表示するAlertを表示
        present(.errorAlert(error: NSError(domain: "hoge", code: 0, userInfo: nil)) { _ in
        // ユーザが閉じたあとに行う処理を記述
        })

        // UITextFieldつきのAlertを表示
        present(.fieldAlert(
            title: "グループの作成", message: "グループ名を入力してください", placeholder: "グループ名",
            handler: { [weak self] (inputText) in
                // 入力されたテキストを使う処理を記述
        }))

        // 0.3秒後に自動で閉じる
        present(.noButtonAlert(title: "✅", message: "保存しました"), 0.3) { [weak self] in
            // ユーザが閉じたあとに行う処理を記述
        }
    }
}

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