ALRT
UIAlertController的一个更简单的构造函数。您可以像这样在任何地方显示一个警告:
ALRT.create(.alert, title: "Alert?").addOK().addCancel().show()
目录
特性
- 可链式 UIAlertController 设置方法
- 支持
.alert
和.actionSheet
UIAlertController 风格 - 支持
UITextField
UIAlertAction(仅限.alert
) - 返回是否成功显示弹窗的
Result
。换句话说,可进行单元测试。
需求
- Xcode 10.2+
- Swift 5.0
- iOS 9.0+
安装
Carthage
github "mshrwtnb/ALRT" ~> 1.3.7
Cocoapods
pod repo update
pod 'ALRT', '~> 1.3.7'
用法
.alert
import ALRT
// Instantiate an .alert-type UIAlertController with OK and Cancel actions. Finally, present the alert by calling `show()`.
ALRT.create(.alert, title: "Title", message: "Message").addOK().addCancel().show()
.actionSheet
// Instantiate an .actionSheet-type UIAlertController.
ALRT.create(.actionSheet, message: "Action Sheet")
.addAction("Option A")
.addAction("Option B")
.addDestructive("Destructive Option")
.show()
动作类型
每个动作都带有不同的 UIAlertAction.Style
。
ALRT.create(.alert, title: "Action Types?")
.addAction("🏂") // .default if not specified
.addOK() // .default
.addCancel("❌") // .cancel
.addDestructive("💣") // .destructive
.show()
自定义标题
OK和取消按钮默认英文标题为"OK"和"Cancel";此处我们将标题改为日文。
ALRT.create(.alert, title: "Actions In Japanese?").addOK("オーケー").addCancel("キャンセル").show()
动作处理
每个动作都有一个 handler
函数,当用户点击动作时会被调用。闭包接收两个参数: UIAlertAction
和 [UITextField]?
。前者是显而易见的。后者在 alert 中添加了文本字段时存在。
ALRT.create(.alert, title: "Action Handling")
.addOK() { action, textFields in
print("\(action.title!) tapped")
}
.show()
结果处理
show()
有一个接收Result
的完成处理函数。你可以确保警报是否成功显示。这在单元测试中非常有用。
ALRT.create(.alert, title: "Result Handling")
.addOK()
.show() { result in
switch result {
case .success:
print("Alert is successfully shown")
case .failure(let error):
print("Error occurred. \(error.localizedDescription)")
}
}
文本字段(s)
在登录等用例中,可以向警报中添加文本字段(s)。
enum TextFieldIdentifier: Int {
case username
case password
}
ALRT.create(.alert, title: "Enter your credentials")
// Configure textfield
.addTextField { textfield in
textfield.placeholder = "Username"
textfield.tag = TextFieldIdentifier.username.rawValue
}
.addTextField() { textField in
textField.placeholder = "Password"
textField.isSecureTextEntry = true
textField.tag = TextFieldIdentifier.password.rawValue
}
// If an user selects "Login", textfields above are retrieved in the trailing closure. Distinguish one from another with a tag or identifier.
.addAction("Login") { _, textfields in
for textField in textfields ?? [] {
if let identifier = TextFieldIdentifier(rawValue: textField.tag) {
switch identifier {
case .username:
// Extract username
case .password:
// Extract password
}
}
}
}
.addCancel()
.show()
将源 ViewController 改为显示的
尽管 ALRT 可以在任何地方显示警告,但你可能出于某种原因需要指定一个源 ViewController。这可以通过传递一个 ViewController 到 show()
来简单地完成。
ALRT.create(.alert, title: "Source?")
.addOK()
.show(self) // self = source view controller
默认配置
设置“确定”和“取消”按钮的默认色调和标题。
ALRT.defaultConfiguration = .init(
tintColor: UIColor.blue,
okTitle: "OK👍",
cancelTitle: "Cancel👎"
)
许可
ALRT是在MIT许可下发布的。 查看许可文件 以获取详细信息。