AlertController TextField Input to Change Text in Label [duplicate] - ios

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!
}
}

Related

In Swift, Commands in alert closure executed before UI alert be executed?

Based on the following code, commands in closure in alert function are executed before User interface be executed. It causes, the variables in closure be empty?
func callAlert2() {
let alert = UIAlertController(title: "Add Contact", message: "Please fill the form", preferredStyle: .alert)
alert.addTextField { textField in
textField.placeholder = "Name"
self.contact.name = textField.text
}
alert.addTextField { (textField) in
textField.placeholder = "Surname"
self.contact.surname = textField.text
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { (action) in
if let name = alert.textFields?.first?.text {
self.allContacts.append(self.contact)
}
}))
self.present(alert, animated: true, completion: nil)
}
Seems like you miss understood addTextField(configurationHandler:) as per docs
A block for configuring the text field prior to displaying the alert.
This block has no return value and takes a single parameter
corresponding to the text field object. Use that parameter to change
the text field properties.
Link: https://developer.apple.com/documentation/uikit/uialertcontroller/1620093-addtextfield
You are expecting your self.contact object's name and surname to be updated inside configuration block but that will never happen. This closure/block is intended only for configuring the textfield and not to capture user input.
Inside this closure you can modify textFields property like placeholder, background color, border etc etc to configure it before being rendered.
But if you want to capture the user input, use actions closure.
Rather
alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { (action) in
if let name = alert.textFields?.first?.text,
(alert.textFields?.count ?? 0) >= 1,
let surname = alert.textFields?[1].text {
self.contact.name = name
self.contact.surname = surname
self.allContacts.append(self.contact)
}
}))
Hope this helps

How can i change uialertcontroller's textfield content?

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.

Swift 4 Alert with Input

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.

Swift: UITextField is not being recognized

I want the user to press a button, and then for them to be able to see an alert where they can enter an input (to set a price for a service). The other logic involves saving data to a database, which is not really relevant to my problem.
I am using the following example:
https://stackoverflow.com/a/30139623/2411290
It definitely works, in that it shows the alert correctly, but once I include
print("Amount: \(self.tField.text)")
"self.tField.text" is not recognized. The specific error I get is:
value of type 'testVC' has no member 'tField'
#IBAction func setAmount(_ sender: Any) {
var tField: UITextField!
func configurationTextField(textField: UITextField!)
{
print("generating textField")
textField.placeholder = "Enter amount"
tField = textField
}
func handleCancel(alertView: UIAlertAction!)
{
print("Cancelled")
}
let alert = UIAlertController(title: "Set price of service", message: "", preferredStyle: .alert)
alert.addTextField(configurationHandler: configurationTextField)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:handleCancel))
alert.addAction(UIAlertAction(title: "Done", style: .default, handler:{ (UIAlertAction) in
print("Done !!")
}))
self.present(alert, animated: true, completion: {
print("completion block")
print("Amount: \(self.tField.text)") // Error here
})
//// other logic for app
}
tField is a local variable inside your setAmount function. It is not a property of the class.
Change:
self.tField.text
to:
tField.text
That will allow you to access the local variable.
But the real question is why are you creating a local variable of UITextField inside this function? Why are you printing its text when the text field isn't used anywhere?
Most likely you should be accessing the alert's text field inside the action handler for the "Done" button. There's no need to do anything inside the completion block of presenting the alert.
#IBAction func setAmount(_ sender: Any) {
let alert = UIAlertController(title: "Set price of service", message: "", preferredStyle: .alert)
alert.addTextField(configurationHandler: { (textField) in
print("generating textField")
textField.placeholder = "Enter amount"
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancelled")
})
alert.addAction(UIAlertAction(title: "Done", style: .default) { (action) in
print("Done !!")
if let textField = alert.textFields?.first {
print("Amount: \(textField.text)")
}
})
self.present(alert, animated: true, completion: nil)
}
My guess is that when you present an alert your current ViewController is the alert viewController... And in your alert there is no variable tField.
On the exampled you quoted the alert was presented only after the print with tField's value. That why that worked there and doesn't work in your case.

How to disable UIAlertController automatic closing when pressing an action button

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.

Resources