迅捷3/4
为了方便起见,可以使用以下扩展名。
内的用法ViewController
:
showInputDialog(title: "Add number",
subtitle: "Please enter the new number below.",
actionTitle: "Add",
cancelTitle: "Cancel",
inputPlaceholder: "New number",
inputKeyboardType: .numberPad)
{ (input:String?) in
print("The new number is \(input ?? "")")
}
扩展代码:
extension UIViewController {
func showInputDialog(title:String? = nil,
subtitle:String? = nil,
actionTitle:String? = "Add",
cancelTitle:String? = "Cancel",
inputPlaceholder:String? = nil,
inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
actionHandler: ((_ text: String?) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
alert.addTextField { (textField:UITextField) in
textField.placeholder = inputPlaceholder
textField.keyboardType = inputKeyboardType
}
alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
guard let textField = alert.textFields?.first else {
actionHandler?(nil)
return
}
actionHandler?(textField.text)
}))
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))
self.present(alert, animated: true, completion: nil)
}
}