ALRTは、UIAlertControllerをシンプルに呼び出すことができるライブラリです。
.alert, .actionSheetのどちらも簡単に作成、表示することができます。
例
ALRT.create(.alert, title: "Show me some alert").addOK().addCancel().show()- ワンライナーでUIAlertControllerを作成、表示
- UIAlertControllerStyle.alert, .actionSheetに対応
- UIAlertControllerにUITextFieldを追加
- 表示結果をResult型でハンドリング
ALRTを使わず、オーソドックスにUIAlertControllerを作成し、表示するにはこのようなコードが必要です。
let alertController = UIAlertController(title: "Show me some alert", message: nil, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)しかし、ALRTを使えば、これだけで済みます。
import ALRT
ALRT.create(.alert, title: "Show me some alert").addOK().addCancel().show()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()UIAlertControllerにUITextFieldを追加することもできます(例:ログイン)。
以下の例では、OKタップ時にUITextFieldの配列を回します。
tagやUITextField変数をスコープ外に用意することで、UITextFieldのtextの取得が可能になります。
ALRT.create(.alert, title: "Login", message: "Please enter your credentials")
.addTextField { textField in
textField.placeholder = "Username"
}
.addTextField { textField in
textField.placeholder = "Password"
textField.isSecureTextEntry = true
}
.addCancel()
.addOK() { _, textFields in
for textField in textFields ?? [] {
// ...
}
}
.show()- Xcode 9.0
- Swift 4.0
- iOS 9.0以上
Podfileに追加
pod "ALRT"
English version can be found here