How to add TextField to Alert View in swift 4? - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

17 Oct 2017

How to add TextField to Alert View in swift 4?

Adding UITextField to alertview became easy from swift 3 by using UIAlertController.

Here we will show step by step.

How to add UITextField to Alert View in swift 4?

Step 1:

First create UIAlertController object with title and message as follow:

let alertVC = UIAlertController(title: "Enter credentials", message: "Provide Email & Password", preferredStyle: .alert)

Step 2:

Next add UITextField's to alertVC using addTextField() method as follow:

alertVC.addTextField { (textField) in
    textField.placeholder = "Email"
}
alertVC.addTextField { (textField) in
    textField.placeholder = "Password"
    textField.isSecureTextEntry = true
}

Step 3:

Then add the UIAlertAction with title and completion handler as follow:

let submitAction = UIAlertAction(title: "Submit", style: .default, handler: {
    (alert) -> Void in
    
    let emailTextField = alertVC.textFields![0] as UITextField
    let passwordTextField = alertVC.textFields![1] as UITextField
    
    print("Email -- \(emailTextField.text!), Password -- \(passwordTextField.text!)")
})

Step 4:

Finally add the UIAlertAction to alertVC and present alertVC as follow:

alertVC.addAction(submitAction)
alertVC.view.tintColor = UIColor.black
present(alertVC, animated: true)

The final output will looks like following image:

uialertcontroller with textfield swift 4

No comments:

Post a Comment

Post Top Ad