DEV Community

Avelyn Hyunjeong Choi
Avelyn Hyunjeong Choi

Posted on • Updated on

UIAlertController taking multiple user inputs

What if there is more than one user input?

Following program will implement an alert that asks the user for username and password. Then log the credentials in the console.

    @IBAction func alertCalled(_ sender: Any) {
        let alert = UIAlertController(title: "Login", message: "Enter username and password", preferredStyle: .alert)

        alert.addTextField() { textField in
            textField.placeholder = "username"
        }

        alert.addTextField() { textField in
            textField.placeholder = "password"
            textField.isSecureTextEntry = true
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
        let yesAction = UIAlertAction(title: "OK", style: .destructive) { _ in
            let usernameTF = alert.textFields![0] as UITextField
            let passwordTF = alert.textFields![1] as UITextField
            guard let username = usernameTF.text, let password = passwordTF.text  else {
                return
            }
            print("Username: \(username) || Password: \(password)")
        }

        alert.addAction(cancelAction)
        alert.addAction(yesAction)

        self.present(alert, animated: true)
    }
Enter fullscreen mode Exit fullscreen mode

result1

result2

Top comments (0)