I am using UIAlertController to getting name variable like this ;
In android my friends can put variables in Alert Controller when alert controller pops up comes like this;
they can put variables in text field and start with it.
But I couldn't, I tried to
alertController.textFields?.first?.text = myNameVariable
but it didn't work.
let alertController = UIAlertController(title: "Update Name", message: nil, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Update", style: .default) { (_) in
if let txtField = alertController.textFields?.first, let text = txtField.text {
// operations
alertController.textFields?.first?.text = "Variable that i already have" // I want to change textfield content
print("Text==>" + text)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = "name"
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}))
sorry for uploading IBB instead of Imgur, in my country Imgur is blocked :/
You need to add the text field before you would access it
here is an example
let alertController = UIAlertController(title: "Update Name", message: nil, preferredStyle: .alert)
alertController.addTextField { textField in
textField.text = "Text goes here 1"
textField.placeholder = "placeholder"
textField.tag = 0
}
alertController.addTextField { textField in
textField.text = "Text goes here 2"
textField.tag = 1
}
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { _ in
let firstTextField = alertController.textFields?.first
let secondTextField = alertController.textFields?.last
print(firstTextField?.text, secondTextField?.text)
}))
Edit
Thanks to #rmaddy
The problem with question's code is that it's trying to set the text field's text after the alert has been dismissed. This makes little sense. Once a user taps one of the alert buttons, the user has already entered text into the text field. The code should be trying to read the user's entered text from the text field, not trying to update the text field's text.
Related
This question already has answers here:
Swift UIAlertController Getting Text Field Text
(2 answers)
Closed 4 years ago.
I'm wanting to change my label "teamNameLabel" whenever a user inputs text into my textfield from AlertController and hit's the ENTER button.
I'm really close. I just need the text once entered to display as my label when the hit the ENTER button.
ALSO: Is there anyway to make the text entered into my textfield CAPITALS ONLY? (eg. User has to enter "TEAM NAME" and not "team name")
See code and images below:
#IBAction func editTeamNameButton() {
let message = "Please Enter Below"
let alert = UIAlertController(title: "ENTER TEAM NAME", message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "ENTER", style: .default, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(action)
alert.addAction(cancelAction)
alert.preferredAction = action
alert.addTextField(configurationHandler: { (textField) in
textField.placeholder = "Eg. TEAM NAME"
})
present(alert, animated: true, completion: nil)
}
Click Here To View Screenshot Of My AlertController
You have to add handler for your UIAlertAction and in this handler you can check if first UITextField in alert's textFields exists, and if exists, you can assign text property of your label as text property of this textField
let action = UIAlertAction(title: "ENTER", style: .default) { _ in
if let textField = alert.textFields?[0] {
self.teamNameLabel.text = textField.text!
}
}
I'm trying to create an alert with two input fields which contain a master password for this app. It's my first app. I saw a function online and wanted to see if it still works but it doesn't seem to pop up with the alert when the function is called. Has this been changed in Swift 4?
func showInputDialog() {
//Creating UIAlertController and
//Setting title and message for the alert dialog
let alertController = UIAlertController(title: "Choose Master Password", message: "Enter your Master and confirm it!", preferredStyle: .alert)
//the confirm action taking the inputs
let confirmAction = UIAlertAction(title: "Enter", style: .default) { (_) in
//getting the input values from user
let master = alertController.textFields?[0].text
let confirm = alertController.textFields?[1].text
if master == confirm {
self.labelCorrect.isHidden = true
self.labelCorrect.text = master
}
}
//the cancel action doing nothing
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
//adding textfields to our dialog box
alertController.addTextField { (textField) in
textField.placeholder = "Enter Master"
}
alertController.addTextField { (textField) in
textField.placeholder = "Confirm Password"
}
//adding the action to dialogbox
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
//finally presenting the dialog box
self.present(alertController, animated: true, completion: nil)
}
//1. Create the alert controller.
let alert = UIAlertController(title: "Title", message: "Description", preferredStyle: .alert)
//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
textField.placeholder = "User"
}
alert.addTextField { (textFieldPass) in
textFieldPass.placeholder = "Password"
textFieldPass.isSecureTextEntry = true
}
// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "Cancelar", style: .default, handler: { [weak alert] (_) in
print("cerrar")
}))
alert.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: { [weak alert] (_) in
let textField = alert?.textFields![0]
let textFieldPass = alert?.textFields![1]
print("Text field: \(textField!.text)")
print("Text field: \(textFieldPass!.text)")
self.Autentificacion(usuario: textField!.text!, clave: textFieldPass!.text!)
}))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)
Going off as a reference to your question and daniel fernando muñoz melendez answer, I have written some code below.
//Create the alert controller.
let alert = UIAlertController(title: "Login", message: "For User", preferredStyle: .alert)
//Add the text field. You can configure it however you need.
alert.addTextField { (userField) in
userField.placeholder = "User"
}
alert.addTextField { (passWordField) in
passWordField.placeholder = "Password"
passWordField.isSecureTextEntry = true
}
//the cancel action doing nothing
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive)
//the confirm action taking the inputs
let acceptAction = UIAlertAction(title: "Enter", style: .default, handler: { [weak alert] (_) in
guard let userField = alert?.textFields?[0], let passWordField = alert?.textFields?[1] else {
print("Issue with Alert TextFields")
return
}
guard let userName = userField.text, let passWord = passWordField.text else {
print("Issue with TextFields Text")
return
}
print("Text field: \(userName)")
print("Text field: \(passWord)")
// Condition Logic
})
//adding the actions to alertController
alert.addAction(acceptAction)
alert.addAction(cancelAction)
// Presenting the alert
self.present(alert, animated: true, completion: nil)
The guard statement for the alert.textFields act as a check to make sure the text fields are in fact created and are not nil.
The guard statement for the userField.text is to make sure that the text in them can be cast to a String. It should be noted that even if the user does not enter anything into the text fields it will still run properly. Since you want them to enter in credentials, I would assume you don't want this to happen and recommend putting your condition logic there. Or have it like daniel fernando muñoz melendez did it and have it in a separate function.
Let me know if you need any clarification.
Wanted to see if there was a way to display an alert view after screenshot is taken, and then require text input that matches a specific string. If the user doesn't input the right text, then the alert view doesn't dismiss and the user is prompted to retry. If the user inputs the correct text, the alert view is dismissed.
You could use this
let requireTextInput = "require text input"
// add observer for screen shot
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil, queue: OperationQueue.main, using:
{ notification in
var inputTextField = UITextField()
let textPrompt = UIAlertController(title: nil, message: "require text input", preferredStyle: .alert)
textPrompt.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
textPrompt.addAction(UIAlertAction(title: "OK", style: .default, handler: {
(action) -> Void in
// if the input match the required text
let str = inputTextField.text
if str == requireTextInput {
print("right")
} else {
print("wrong")
}
}))
textPrompt.addTextField(configurationHandler: {(textField: UITextField!) in
textField.placeholder = "place Holder"
inputTextField = textField
})
self.present(textPrompt, animated: true, completion: nil)
})
I have an UIAlertController and i'm checking for user input. When the user doesn't type in text field, the OK Action button i added should give the user a warning and not close the alert view.
I handle the warning but the alert view closes automatically.
How can i disable the automatic closing?
Thanks.
MY CODE:
var alert = UIAlertController(title: "change name and phone number", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,
handler: { action in
//Add a comment to this line
let nameField: UITextField = alert.textFields![0] as UITextField
let phoneField: UITextField = alert.textFields![1] as UITextField
let name = nameField.text
let phone = phoneField.text
if name.length == 0 {
JLToast.makeText("Please enter name").show()
} else if phone.length == 0 {
JLToast.makeText("Please enter phone number").show()
} else {
self.sendSupportInfo(nameField.text, phone: phoneField.text)
}
println("name:: \(nameField.text), phone: \(phoneField.text)")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
alert.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "name"
}
alert.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "0544-444444"
textField.keyboardType = UIKeyboardType.PhonePad
}
self.presentViewController(alert, animated: true, completion: nil)
You can not do that.
Other option is, you can only disable the UIAlertAction.
Instead, you might want to create your own custom dialog to that.
as the offical documentation say:
Subclassing
The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.
U can create a new UI window and make the window level above the alert level and then show your alert onto the new UIwindow.
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 the value from the alert.
Updated for Swift 3 and above:
//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)
//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
textField.text = "Some default text"
}
// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert.textFields![0] // Force unwrapping because we know it exists.
print("Text field: \(textField.text)")
}))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)
Swift 2.x
Assuming you want an action alert on iOS:
//1. Create the alert controller.
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)
//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.text = "Some default text."
})
//3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
let textField = alert.textFields![0] as UITextField
println("Text field: \(textField.text)")
}))
// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)
Swift 5
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, actionHandler:
{ (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)
}
}
In Swift5 ans Xcode 10
Add two textfields with Save and Cancel actions and read TextFields text data
func alertWithTF() {
//Step : 1
let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
//Step : 2
let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
let textField = alert.textFields![0] as UITextField
let textField2 = alert.textFields![1] as UITextField
if textField.text != "" {
//Read TextFields text data
print(textField.text!)
print("TF 1 : \(textField.text!)")
} else {
print("TF 1 is Empty...")
}
if textField2.text != "" {
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
}
//Step : 4
alert.addAction(save)
//Cancel action
let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
alert.addAction(cancel)
//OR single line action
//alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
self.present(alert, animated:true, completion: nil)
}
For more explanation https://medium.com/#chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c
Swift version: 5.+
Create a new TextField variable in current scope and assign it to alertTextField in alert.addTextField completion handler. Use textField's value inside UIAlertAction completion handler.
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
//Variable to store alertTextField
var textField = UITextField()
let alert = UIAlertController(title: "Add new item", message: "", preferredStyle: .alert)
alert.addTextField { alertTextField in
alertTextField.placeholder = "Create new item"
//Copy alertTextField in local variable to use in current block of code
textField = alertTextField
}
let action = UIAlertAction(title: "Add item", style: .default) { action in
//Prints the alertTextField's value
print(textField.text!)
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
let ac = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
ac.addTextField()
let submitAction = UIAlertAction(title: "Submit", style: .default) { [weak self, weak ac] action in
guard let wordToget = ac?.textFields?[0].text else { return }
//here you can do what you need like
print(wordToget)
}
ac.addAction(submitAction)
present(ac, animated: true)