Get Input Value from Textfield in iOS Alert in Swift

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 to get the string from user input in alert textfield

You will get that once user pressed Add item not before that where you are trying to print it.

check below code:

let addItemAction = UIAlertAction(title: "Add item", style: .default) { (action) in

// after user click "add item", the new item will be displayed to table view
print(textField.text) //Here you will get user text.

let newItem = Item()
newItem.title = textField.text //add it here
self.itemArray.append(newItem)
self.saveItems()
}

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'

Is there way to get the text field value in UIAlertAction?

A swifty way is to add a temporary variable for the text field and a handler to assign the text field of the alert to the variable

func showAlert() {
weak var textField : UITextField?

let editAction = UIAlertAction(title: "Edit", style: .destructive) { _ in
print("Edit Pressed", textField?.text ?? "n/a")
}
let handler : (UITextField) -> Void = { textField = $0 }
self.showAlertWithTextField(title: "test", message: nil, actions: [editAction], style: .alert, handler: handler, completion: nil)

}

In the extension call the handler right after the text field has beed added

extension UIViewController {

func showAlertWithTextField(title: String?, message: String?,
actions: [UIAlertAction],
style: UIAlertController.Style,
handler: ((UITextField) -> Void)? = nil,
completion: (() -> Void)?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
alert.addTextField { handler?($0) }
actions.forEach { alert.addAction($0)}
present(alert, animated: true, completion: nil)
}
}

Getting text value from alert box

your ok action handler(closure) will call when you click on ok button. so instead of assign value to local variable sessionName , make a sessionName variable in class.

class YourClass {
var sessionName: String?

...

@IBAction func btnSaveSession(sender: AnyObject) {

//Prompt user to enter session name

promptUserToEnterSessionName("Save Session", message: "Please enter the name of your custom session below.");

}

func promptUserToEnterSessionName(title: String, message: String) {

//1. Create the alert controller.
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.text = "Enter session name."
})

//3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
let textField = alert.textFields![0] as UITextField
print("Text field: \(textField.text)")
self.sessionName = textField.text!
self.testDemo()
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

}

fun TestDemo() {
print("session Name: " + self.sessionName)

//Save session to firebase.

//redirect to create session controller.

}
}

How to limit and alert textfield input values from decimalPad in Swift4?]

I get an reference from here

First add UITextFieldDelegate to your controller like this

class ViewController: UIViewController, UITextFieldDelegate 

add this in viewDidLoad

    yourTextField.delegate = self

and then

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
let withDecimal = (
string == NumberFormatter().decimalSeparator &&
textField.text?.contains(string) == false
)
return isNumber || withDecimal
}

How can I get following pop up text field in Swift?

It's going to look something like this:

// create the actual alert controller view that will be the pop-up
let alertController = UIAlertController(title: "New Folder", message: "name this folder", preferredStyle: .alert)

alertController.addTextField { (textField) in
// configure the properties of the text field
textField.placeholder = "Name"
}

// add the buttons/actions to the view controller
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let saveAction = UIAlertAction(title: "Save", style: .default) { _ in

// this code runs when the user hits the "save" button

let inputName = alertController.textFields![0].text

print(inputName)

}

alertController.addAction(cancelAction)
alertController.addAction(saveAction)

present(alertController, animated: true, completion: nil)

Let me know if this helps.



Related Topics



Leave a reply



Submit