1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】UIAlertControllerを簡略化してみよう

Last updated at Posted at 2021-03-28

はじめに

UIAlertControllerを使うときにアクションなどが多いと同じ処理を何回も複数のファイルに書いたりするのって少し面倒ですよね。
そんな時に簡略化できないかを考えてみます。

やりたいこと

let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert)
        let action1 = UIAlertAction(title: "ボタン1", style: .default, handler: { (_) in
            print("button1")
        })
        let action2 = UIAlertAction(title: "ボタン2", style: .default, handler: { (_) in
            print("button2")
        })
        let action3 = UIAlertAction(title: "ボタン3", style: .default, handler: { (_) in
            print("button3")
        })
        alert.addAction(action1)
        alert.addAction(action2)
        alert.addAction(action3)
present(alert, animated: true, completion: nil)

これを、省略していきましょう。

実装

メソッドチェーンを使うので、前回と同じようなことをします。
ポイントはreturn selfです。

extension UIViewController {
    func Alert(title: String, message: String) -> UIAlertController {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        return alert
    }
}

extension UIAlertController {
    func addAction(title: String, action: @escaping () -> Void) -> Self {
        addAction(UIAlertAction(title: title, style: .default, handler: { _ in action() }))
        return self
    }
}

このように書くと、

let alert = Alert(title: "タイトル", message: "メッセージ")
    .addAction(title: "ボタン1", action: { print("button1") })
    .addAction(title: "ボタン2", action: { print("button2") })
    .addAction(title: "ボタン3", action: { print("button3") })
present(alert, animated: true)

このようにシンプルに書くことができます。

おわりに

チーム開発などでは独自の書き方はあまりお勧めできませんが、、、

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?