Swift 3/4
You can use the extension below for your convenience.
Use inside 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 Code:
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: .destructive, 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) } }
Gunhan Jan 02 '18 at 18:16 2018-01-02 18:16
source share