Get input value from TextField in iOS alert in Swift

后端 未结 3 1003
不知归路
不知归路 2020-12-07 10:48

I\'m trying to make an alert message with input, and then get the value from the input. I\'ve found many good tutorials how to make the input text field. but I can\'t get th

3条回答
  •  一整个雨季
    2020-12-07 11:24

    Swift 3/4

    You can use the below extension for your convenience.

    Usage inside a 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 ?? "")")
    }
    

    The 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: .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)
        }
    }
    

提交回复
热议问题