はじめに
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)
このようにシンプルに書くことができます。
おわりに
チーム開発などでは独自の書き方はあまりお勧めできませんが、、、