UIAlertControllerを簡単に使うためのライブラリALRTがSwift 4.1に対応しました
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
- @shimesabaさんにレビューいただいておりました。ありがとうございます。