Access input from UIAlertController
I know comments have been posted to answer the question, but an answer should make the solution explicit.
@IBOutlet var newWordField: UITextField
func wordEntered(alert: UIAlertAction!){
// store the new word
self.textView2.text = deletedString + " " + self.newWordField.text
}
func addTextField(textField: UITextField!){
// add the text field and make the result global
textField.placeholder = "Definition"
self.newWordField = textField
}
// display an alert
let newWordPrompt = UIAlertController(title: "Enter definition", message: "Trainging the machine!", preferredStyle: UIAlertControllerStyle.Alert)
newWordPrompt.addTextFieldWithConfigurationHandler(addTextField)
newWordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
newWordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: wordEntered))
presentViewController(newWordPrompt, animated: true, completion: nil)
This displays a prompt with a text field and two action buttons. It reads the text field when done.
How to get text input out of UIAlertcontroller OR how to wait for the input using Swift
Of course you get crash, shortName
is nil while Submit button isn't pressed. You can try something like this:
@IBAction func saveFile(sender: AnyObject) {
var alertController:UIAlertController?
alertController = UIAlertController(title: "Enter File",
message: "Enter file name below",
preferredStyle: .Alert)
alertController!.addTextFieldWithConfigurationHandler(
{(textField: UITextField!) in
textField.placeholder = ""
})
let action = UIAlertAction(title: "Submit",
style: UIAlertActionStyle.Default,
handler: {[weak self]
(paramAction:UIAlertAction!) in
if let textFields = alertController?.textFields{
let theTextFields = textFields as [UITextField]
let enteredText = theTextFields[0].text
self!.shortName = enteredText //trying to get text into shortName
print(self!.shortName) // prints
self?.handleText()
NSOperationQueue.mainQueue().addOperationWithBlock({
self?.handleTextInMainThread()
})
}
})
alertController?.addAction(action)
self.presentViewController(alertController!,
animated: true,
completion: nil)
}
func handleText() {
print(self.shortName)
}
func handleTextInMainThread() {
print(self.shortName)
}
You have use NSOperationQueue
if you want to work with UI inside handleTextInMainThread
after user's input.
How do i get a value of textField in an UIAlertController?
Try this code :
var inputTextField: UITextField?
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
// Do whatever you want with inputTextField?.text
println("\(inputTextField?.text)")
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in
}
alertController.addAction(ok)
alertController.addAction(cancel)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
inputTextField = textField
}
presentViewController(alertController, animated: true, completion: nil)
Swift UIAlertController Getting Text Field Text
The UIAlertController has a textFields
property. That's its text fields. Any of your handlers can examine it and thus can get the text from any of the text fields.
Get input value from TextField in iOS alert in Swift
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)
How do I observe user editing a textField in an UIAlertController?
You can try to get a reference to it with self.textF = alert.textFields?[0]
class ViewController: UIViewController {
var textF:UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = "Some default text"
}
let tex = alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
}))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)
self.textF = alert.textFields?[0]
self.textF.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControl.Event.editingChanged)
}
}
@objc func textFieldDidChange() {
print(textF.text)
}
}
Accessing UIAlertControllers textField
All you need to do, is to unwrap the array of UITextFields and then cast it to a UITextField because it's actually a array of AnyObject.
Here is what the code should look like:
var text = (alert.textFields![0] as UITextField).text
How to get the input text from the TextField in an alert
You need to use the same logic as in Swift
: write alert.textFields[0].text
inside the action handler in the following way:
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *input = alert.textFields[0].text;
NSLog(@"input was '%@'", input);
}];
Which in my test prints
input was '1234'
Related Topics
Swift Xcode Index Freezing or Slow
Swiftui - Is There a Popviewcontroller Equivalent in Swiftui
Module Compiled With Swift 3.0 Cannot Be Imported in Swift 3.0.1
How to Document the Parameters of a Function'S Closure Parameter in Swift 3
What's the Difference Between Using Aranchor to Insert a Node and Directly Insert a Node
How to Restrict Certain Characters in Uitextfield in Swift
How to Use Generic Types to Get Object with Same Type
Querying Below Autoid's in Firebase
Masking an Image in Swift Using Calayer and Uiimage
Swift Generics: Requiring Addition and Multiplication Abilities of a Type
How to Convert Timeinterval into Minutes, Seconds and Milliseconds in Swift
Extension of Dictionary Where <String, Anyobject>
Swift: Determine What Object Called a Function
Swift 2.0: Protocol Extensions: Two Protocols with the Same Function Signature Compile Error