How to add TextField to UIAlertController in Swift

前端 未结 13 709
余生分开走
余生分开走 2020-12-07 20:03

I am trying to show a UIAlertController with a UITextView. When I add the line:

    //Add text field
    alertController.addTextFie         


        
相关标签:
13条回答
  • 2020-12-07 20:15

    UIAlertController with UITextfield in latest Apple Swift version 5.1.3

    Create a lazy variable of UIAlertController in your UIViewController , Add UITextFieldDelegate , Show Alert on UIButton Action :

    class  YourViewController: UIViewController,UITextFieldDelegate {
    
        //Create Alert Controller Object here
        lazy var alertEmailAddEditView:UIAlertController = {
    
            let alert = UIAlertController(title:"My App", message: "Customize Add/Edit Email Pop Up", preferredStyle:UIAlertController.Style.alert)
    
            //ADD TEXT FIELD (YOU CAN ADD MULTIPLE TEXTFILED AS WELL)
            alert.addTextField { (textField : UITextField!) in
                textField.placeholder = "Enter  emails"
                textField.delegate = self
            }
    
            //SAVE BUTTON
            let save = UIAlertAction(title: "Save", style: UIAlertAction.Style.default, handler: { saveAction -> Void in
                let textField = alert.textFields![0] as UITextField
                print("value entered by user in our textfield is: \(textField.text)")
            })
            //CANCEL BUTTON
            let cancel = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: {
                (action : UIAlertAction!) -> Void in })
    
    
            alert.addAction(save)
            alert.addAction(cancel)
    
            return alert
        }()
    
    
        //MARK:- UIButton Action for showing Alert Controller
        @objc func buttonClicked(btn:UIButton){
            self.present(alertEmailAddEditView, animated: true, completion: nil)
        }
    
        //MARK:- UITextFieldDelegate
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            return true
        }
    }
    

    Happy Coding!! :)

    0 讨论(0)
  • 2020-12-07 20:23
    private func showLoginAlert() {
        let loginAlert = UIAlertController(title: "Login Using Credentials", message: nil, preferredStyle: .alert)
        loginAlert.view.tintColor = .systemBlue
    
        loginAlert.addTextField { usernameField in
            usernameField.font = .systemFont(ofSize: 17.0)
            usernameField.placeholder = "Username"
        }
        loginAlert.addTextField { passwordField in
            passwordField.font = .systemFont(ofSize: 17.0)
            passwordField.isSecureTextEntry = true
            passwordField.placeholder = "Password"
        }
    
        let cancelAction = UIAlertAction(title: "Cancel",
                                         style: .destructive,
                                         handler: { _ in
                                            // self.handleUsernamePasswordCanceled(loginAlert: loginAlert)
        })
        loginAlert.addAction(cancelAction)
    
        let loginAction = UIAlertAction(title: "Login",
                                        style: .default,
                                        handler: { _ in
                                            // self.handleUsernamePasswordEntered(loginAlert: loginAlert)
        })
        loginAlert.addAction(loginAction)
        loginAlert.preferredAction = loginAction
        present(loginAlert, animated: true, completion: nil)
    }
    

    Swift 5

    0 讨论(0)
  • 2020-12-07 20:25

    Solution:

    Swift 4.2

    Try the following lines and see if it works:

    let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
    
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter Second Name"
    }
    
    let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
        let firstTextField = alertController.textFields![0] as UITextField
        let secondTextField = alertController.textFields![1] as UITextField
    })
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil )
    
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter First Name"
    }
    
    alertController.addAction(saveAction)
    alertController.addAction(cancelAction)
    
    self.present(alertController, animated: true, completion: nil)
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-07 20:26

    For Swift 4.0, You can use this sample of code succesfully tested in my project:

    @IBAction func withdrawTapped(_ sender: UIButton) {
    
      let alertController = UIAlertController(title: "Token withdraw", message: "", preferredStyle: .alert)
    
      let withdrawAction = UIAlertAction(title: "Withdraw", style: .default) { (aciton) in
    
        let text = alertController.textFields!.first!.text!
    
        if !text.isEmpty {
          self.presentAlert(
            title: "Succesful", 
            message: "You made request for withdraw \(textField.text) tokens")
        }
      }
    
      let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
      }
    
      alertController.addTextField { (textField) in
        textField.placeholder = "999"
        textField.keyboardType = .decimalPad
      }
    
      alertController.addAction(withdrawAction)
      alertController.addAction(cancelAction)
    
      self.present(alertController, animated: true, completion: nil)
    }
    
    0 讨论(0)
  • 2020-12-07 20:27

    So I started checking to see what could possibly have been different in my code to the working code. I noticed that my ViewController extends

    UITextFieldDelegate
    

    Which apparently means that I need to set the delegate of any child UITextView:

    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
        searchTextField = textField
        searchTextField?.delegate = self //REQUIRED
        searchTextField?.placeholder = "Enter your search terms"
    }
    
    0 讨论(0)
  • 2020-12-07 20:29

    In Swift 4.2 and Xcode 10.1

    Alert with two Textfields and Read TextField text data and present alert on top of all views.

    func alertWithTF(title: String, message: String) {
        //Step : 1
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    
        //Step : 2
        alert.addAction (UIAlertAction(title: "Save", style: .default) { (alertAction) in
            let textField = alert.textFields![0]
            let textField2 = alert.textFields![1]
            if textField.text != "" {
                //Read textfield data
                print(textField.text!)
                print("TF 1 : \(textField.text!)")
            } else {
                print("TF 1 is Empty...")
            }
            if textField2.text != "" {
                //Read textfield data
                print(textField2.text!)
                print("TF 2 : \(textField2.text!)")
            } else {
                print("TF 2 is Empty...")
            }
        })
    
        //Step : 3
        //For first TF
        alert.addTextField { (textField) in
            textField.placeholder = "Enter your first name"
            textField.textColor = .red
        }
        //For second TF
        alert.addTextField { (textField) in
            textField.placeholder = "Enter your last name"
            textField.textColor = .blue
        }
    
        //Cancel action
        alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
       self.present(alert, animated:true, completion: nil)
    
    }
    

    If you want to present aleert on top of all views.

    Here from above code remove this last line self.present(alert, animated:true, completion: nil) and add below code.

    //Present alert on top of all views.
    let alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()
    alertWindow.windowLevel = UIWindowLevelAlert + 1
    
    alertWindow.makeKeyAndVisible()
    
    alertWindow.rootViewController?.present(alert, animated:true, completion: nil)
    

    Now call like this

    alertWithTF(title: "This is title", message: "This is message")
    
    0 讨论(0)
提交回复
热议问题