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.
Related
I want to add function such as, if there are no any letters in textfield and press confirm button, than textfield print "you must need to write folder name", and stop action while there print is showing. I was find something examples in google, but I don't know how adjust with my code.
func folderAddAlert() {
let alert = UIAlertController(title: "Folder name", message: nil, preferredStyle: .alert)
alert.addTextField {(folderAddTF) in folderAddTF.placeholder = "Please add folder name"
print("+ clicked." )
}
let action = UIAlertAction(title: "Confirm", style: .default){ (_) in
guard let folder = alert.textFields?.first?.text else { return }
print("folderName: \(folder)")
self.folderNames.append(folder)
self.collectionView.reloadData()
}
let cancel = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(action)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
}
you are in the right way, but in here you need check the textfield is empty or not on your validation on user press the Confirm button like this
let action = UIAlertAction(title: "Confirm", style: .default){ (_) in
guard let folder = alert.textFields?.first?.text, !folder.isEmpty else {
self.present(alert, animated: true, completion: nil)
if let getPlaceholder = alert.textFields?.first, let placeHolderText = getPlaceholder.placeholder{
getPlaceholder.attributedPlaceholder = NSAttributedString(string: placeHolderText,
attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
}
return }
print("folderName: \(folder)")
}
Here is my code. When I press "Download" button my "someVariable" global variable doesn't change. I tried to debug it in the debugger but couldn't find the issue.
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
let textField = UITextField()
let alert = UIAlertController(title: "Download URL", message: "", preferredStyle: .alert)
alert.addTextField { (actionTextField) in
actionTextField.placeholder = "Paste link here"
}
let action = UIAlertAction(title: "Download", style: .default) { (action) in
self.someVariable = textField.text!
}
let secondAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(action)
alert.addAction(secondAction)
present(alert, animated: true, completion: nil)
}
Welcome to Stackoverflow. Your textField in line 2 is what you're getting your someVariable's new value from. I'm supposing you want to get the value from your alert's textField instead.
You can get reference from your alert's textField through your alert's textFields property, like so:
let action = UIAlertAction(title: "Download", style: .default) { (action) in
guard let textField = alert.textFields?.first else { return }
self.someVariable = textField.text!
}
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.
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'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)