LoginSignup
51
49

More than 5 years have passed since last update.

UIAlertControllerを簡単に使う!ALRTがSwift 4.1に対応しました

Last updated at Posted at 2016-07-31

UIAlertControllerを簡単に使うためのライブラリALRTがSwift 4.1に対応しました:metal_tone1:
https://github.com/mshrwtnb/ALRT

ALRT ?

ALRTは、UIAlertControllerを簡単に呼び出すことができるライブラリです。
.alert, .actionSheet両方のpreferredStyleに対応しています。

ALRT.create(.alert, title: "Show me some alert").addOK().addCancel().show()

実行環境

  • Xcode 9.3
  • Swift 4.1
  • iOS 9.0以上

インストール方法

Cocoapods

pod "ALRT"

Carthage

github "mshrwtnb/ALRT" ~> 1.2.0

サンプルコード

例1 .alert表示

ALRTを使わず、オーソドックスにUIAlertControllerを作成し、表示するにはこのようなコードが必要です。

let alertController = UIAlertController(title: "Show me some alert", preferredStyle: .alert)

let okAction = UIAlertAction(title: "OK", style: .default)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alertController.addAction(okAction)
alertController.addAction(cancelAction)

self.present(alertController, animated: true)

しかし、ALRTを使えば、これだけで済みます。

import ALRT
ALRT.create(.alert, title: "Show me some alert").addOK().addCancel().show()

例2 .actionSheet表示、Actionタップをハンドリング

UIAlertActionのタップハンドリングはTrailing Closureで行うことができます。

以下の例ではタップされるとメッセージがprintされます。

ALRT.create(.actionSheet, title: "ALRT", message: "Show me some action sheet")
    .addAction("Option A") { _, _ in print("Option A has been tapped!") }
    .addAction("Option B") { action, textfield in print("\(action.title!) has been tapped!") }
    .addDestructive("Destructive Option")
    .show()

独自アラートを定義しておきたい場合

// 例: 通信エラー
extension ALRT {
    class func showNetworkError() {
        ALRT.create(.alert, title: "Network Error", message: "Check your internet connection and try again")
             .addOK()
             .show()
    }
}

ALRT.showNetworkError()

Special Thanks

51
49
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
51
49