I am trying to show a UIAlertController
with a UITextView
. When I add the line:
//Add text field
alertController.addTextFie
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!! :)