LoginSignup
10
4

More than 5 years have passed since last update.

UIAlertController を楽に書く為の最高のライブラリを作りました (◍•ᴗ•◍)

Last updated at Posted at 2018-03-25

概要

iOS アプリにおいて UIAlertController はユーザーに確認を取ったり、選択をしたりするときによく使う UI です.

しかしながら使うために書くコードの量が多く、しかも単調で辛いです.

そこでいい感じにかけるライブラリを作りました. ->
https://github.com/mironal/ShortHandAlert

問題提起

繰り返しになりますが UIAlertController を使うためのコードは長いです. こんな感じです.


let alert = UIAlertController(title: "title", message: nil, preferredStyle: .actionSheet)


 alert.addAction(UIAlertAction(title: "Some", style: .default, handler: { _ in
     print("do something...")
 }))

 alert.addAction(UIAlertAction(title: "Another", style: .default, handler: { _ in
     print("do something...")
 }))

 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))

 present(alert, animated: true)

上の例は3つのアクションを持つアクションシートです. 縦にも横にも長いですね.

僕は特に addAction(UIAlertAction(ほんにゃらかんにゃら)) って書くところがごちゃごちゃするのでとても辛くて心を無にしてタイピングしています.

ライブラリ

そこでいい感じのは無いかな〜〜と思い github を探したのですが、どれも冗長だったので気持ちよく書けるやつを自作しました.

↓ これです.
https://github.com/mironal/ShortHandAlert

先に述べた大変つらいコードと同等のことをするコードは以下のとおりです.

UIAlertController(title: "Title", message: nil, preferredStyle: .actionSheet)
    .default("Some") {
        print("do something...")
    }
    .destructive("Another") {
        print("do something...")
    }
    .cancel()
    .present(in: self)

とてもスッキリと書けます. 特に横幅が短くて済むので好きです.

UIAlertController の extension として作ってあるので新たに覚えることは殆ど無く簡単に使い始めることができます.

また、 AlertBuilder というよく使う Alert を簡単に作るための Builder クラスも作ってあります.

こんな感じに使えます.

AlertBuilder()
    .confirm(title: nil, message: "Some message")
    .approve()
    .present(in: self)

エラーを表示するだけならこんな感じ.

AlertBuilder()
    .confirm(error: error)
    .approve() { _ in /* OK 押した後に何かしたいならここに書く. */ }
    .present(in: self)

これは戻り値をいい感じに設計してあるので補完候補がいい感じに出るようになっています. UIAlertController の extension として書いた部分が補完を汚すのでそれを解決するためにこいつを作りました.

簡単な Alert を作るときは AlertBuilder を使ってそれ以外は UIAlertController の extension を使うのがおすすめです.

より詳しくは READMEAPI ドキュメントをご確認ください.

インストール

インストールは Carthage を使うのをおすすめしています. コードが2つしか無いので自分のプロジェクトにそのままコピーしてもいいと思います.

使いたくなったらぜひともスターをお願いします. https://github.com/mironal/ShortHandAlert

10
4
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
10
4