How to add textField in UIAlertController? - ios

I want to realize a function about changing password. It requires users to input their previous password in an alert dialog.
I want to click the button "Confirm the modification" then jump to the other view controller for changing password. I have written some code, but I don't know how to write in the next moment.
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Change password" message:#"Please input your previous password" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = #"please input your previous password";
textField.secureTextEntry = YES;
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"cancel" style:UIAlertActionStyleCancel handlers:nil];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"Confirm the modification" style:UIAlertActionStyleDestructive handler:*(UIAlertAction *alertAction) {
if (condition) {
statements
}
}];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];

You will get all added textfields from alert controller by its textFields readonly property, you can use it to get its text.
Like
Swift 4:
let alertController = UIAlertController(title: "", message: "", preferredStyle: .alert)
alertController.addTextField { textField in
textField.placeholder = "Password"
textField.isSecureTextEntry = true
}
let confirmAction = UIAlertAction(title: "OK", style: .default) { [weak alertController] _ in
guard let alertController = alertController, let textField = alertController.textFields?.first else { return }
print("Current password \(String(describing: textField.text))")
//compare the current password and do action here
}
alertController.addAction(confirmAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
Note: textField.text is optional, unwrap it before using
Objective-C:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"" message:#"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = #"Current password";
textField.secureTextEntry = YES;
}];
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(#"Current password %#", [[alertController textFields][0] text]);
//compare the current password and do action here
}];
[alertController addAction:confirmAction];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(#"Canelled");
}];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
By [[alertController textFields][0] text] this line, it will take first textfield added to the alerController and get its text.

You can add multiple textfields to alert controller and access them with the alert controller's textFields property
If the new password is an empty string, present the alert again. Or another way would be to disable the "Confirm" button, enabling it only when text field has text.
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"confirm the modification" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
UITextField *password = alertController.textFields.firstObject;
if (![password.text isEqualToString:#""]) {
//change password
}
else{
[self presentViewController:alertController animated:YES completion:nil];
}
}];

Here is an updated answer for Swift 4.0 that creates the desired kind of textfield:
// Create a standard UIAlertController
let alertController = UIAlertController(title: "Password Entry", message: "", preferredStyle: .alert)
// Add a textField to your controller, with a placeholder value & secure entry enabled
alertController.addTextField { textField in
textField.placeholder = "Enter password"
textField.isSecureTextEntry = true
textField.textAlignment = .center
}
// A cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Canelled")
}
// This action handles your confirmation action
let confirmAction = UIAlertAction(title: "OK", style: .default) { _ in
print("Current password value: \(alertController.textFields?.first?.text ?? "None")")
}
// Add the actions, the order here does not matter
alertController.addAction(cancelAction)
alertController.addAction(confirmAction)
// Present to user
present(alertController, animated: true, completion: nil)
And how it looks when first presented:
And while accepting text:

Swift 5.1
#objc func promptAddDialog() {
let ac = UIAlertController.init(title: "Enter answer", message: nil, preferredStyle: .alert)
ac.addTextField{ textField in
textField.placeholder = "Answer"
textField.textAlignment = .center
}
let submitAction = UIAlertAction(title: "Submit", style: .default) {
[weak self, weak ac] _ in
guard let answer = ac?.textFields?[0].text else { return }
self?.submit(answer)
}
ac.addAction(submitAction)
present(ac, animated: true)
}

Related

how to use UIAlertController

I am trying to use this code in a Pacman game I got from some website but had to change UIAlertView to UIAlertController except the following code has two errors that I don't know how to fix (I am really new to programming and feel like this is a really newbie question - sorry!!)
The first error is in line 4: No known class method for selector alertControllerWithTitle
A second error is in the last line: no visible interface declares the selector show
- (void)collisionWithExit: (UIAlertController *)alert {
if (CGRectIntersectsRect(self.pacman.frame, self.exit.frame)) {
[self.motionManager stopAccelerometerUpdates];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Congratulations"
message:#"You've won the game!"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil
preferredStyle:UIAlertControllerStyleAlert];
[alert show];
}
}
Please check the following code:
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"My Alert"
message:#"This is an alert."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
Check below this code.
for Objective-C:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Alert" message:#"Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//button click event
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:cancel];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
for Swift 4.x:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style {
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}
}))
self.present(alert, animated: true, completion: nil)
Swift 5: Simple Extension
extension UIViewController {
func presentAlert(withTitle title: String, message : String, actions : [String: UIAlertAction.Style], completionHandler: ((UIAlertAction) -> ())? = nil) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for action in actions {
let action = UIAlertAction(title: action.key, style: action.value) { action in
if completionHandler != nil {
completionHandler!(action)
}
}
alertController.addAction(action)
}
self.present(alertController, animated: true, completion: nil)
}
}
Usage:
self.presentAlert(withTitle: "Network Error", message: "Please check your internet connection", actions: [
"Retry" : .default, "Cancel": .destructive] , completionHandler: {(action) in
if action.title == "Retry" {
print("tapped on Retry")
}else if action.title == "Cancel" {
print("tapped on Cancel")
}
})
OR
self.presentAlert(withTitle: "Mail services are not available", message: "Please Configure Mail On This Device", actions: ["OK" : .default] , completionHandler: nil)

UILabel in UIAlertController or UITextField alike UILabel

I need to add some labels to UIAlertController and after researching it turned out that there is no normal way to do it. But as it's possible to add UITextField, I decided to change UITextField's appearance to be alike UILabel (has no border and background color). But changing its background color to clear and border style to none doesn't help. How can I achieve this?
Here is the code:
- (void)test
{
UIAlertController * alert = [UIAlertController alertControllerWithTitle:#"Test Title"
message:#"Test Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Do Some action here
}];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.text = #"Text: ";
textField.backgroundColor = [UIColor blueColor];
textField.borderStyle = UITextBorderStyleNone;
textField.backgroundColor = [UIColor clearColor];
[textField setUserInteractionEnabled:NO];
}];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
}];
[self presentViewController:alert animated:YES completion:nil];
}
Update:
Here is what I get:
And here is what I trying to do:
I believe you want to add a custom Label in UIAlert for good UI Look.
The best way to do this either programming a custom UIView such that it feels and behaves like an UIAlertView or use one of the following libraries from github.
https://github.com/nealyoung/NYAlertViewController
https://github.com/sberrevoets/SDCAlertView
use this
textField.placeholder = #"Text: ";
instead of
textField.text = #"Text: ";
There is no need of third party libs to achieve this. Just customize UIAlertController
let alertController = UIAlertController(title: "Add Table", message: "", preferredStyle: UIAlertController.Style.alert)
alertController.addTextField { (textField) -> Void in
textField.text = "No of Columns :"
textField.keyboardType = .numberPad
textField.isUserInteractionEnabled = false
}
alertController.addTextField { (textField) -> Void in
textField.placeholder = "No of Columns"
textField.keyboardType = .numberPad
textField.text = "2"
textField.isUserInteractionEnabled = false
}
alertController.addTextField { (textField) -> Void in
textField.text = "No of Rows :"
textField.keyboardType = .numberPad
textField.isUserInteractionEnabled = false
}
alertController.addTextField { (textField) -> Void in
textField.placeholder = "No of Rows"
textField.keyboardType = .numberPad
textField.text = "2"
}
let saveAction = UIAlertAction(title: "Create", style: UIAlertAction.Style.default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
let secondTextField = alertController.textFields![1] as UITextField
})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.destructive, handler: {
(action : UIAlertAction!) -> Void in })
alertController.addAction(cancelAction)
alertController.addAction(saveAction)
if let textFields = alertController.textFields {
if textFields.count > 0{
textFields[0].superview!.superview!.subviews[0].removeFromSuperview()
textFields[0].superview!.backgroundColor = UIColor.clear
}
if textFields.count > 2{
textFields[2].superview!.superview!.subviews[0].removeFromSuperview()
textFields[2].superview!.backgroundColor = UIColor.clear
}
}
self.present(alertController, animated: true, completion: nil)

Change title color in UIAlertController

I have two button but I just wanna change one to red.When I use the function below
it change all to red. I just want to change color of only one button. How can i do it?
alertController.view.tintColor = UIColor.redColor()
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
alertController.setValue(NSAttributedString(string: title, attributes: [NSFontAttributeName : UIFont.appFont_OpenSans_Regular(fontSize: 15),NSForegroundColorAttributeName : BLACK_COLOR]), forKey: "attributedTitle")
alertController.setValue(NSAttributedString(string: message, attributes: [NSFontAttributeName : UIFont.appFont_OpenSans_Regular(fontSize: 13),NSForegroundColorAttributeName : APP_COLOR_BLUE_1]), forKey: "attributedMessage")
You can try this,
deleteAction.setValue(color, forKey: titleTextColor)
It works for me!
Swift
you need to use UIAlertActionStyle.Destructive for button text color in red
let alert = UIAlertController(
title: "Basic alert style",
message: "Basic alert With buttons",
preferredStyle: .alert )
let Reset = UIAlertAction(
title: "Reset",
style: .destructive) { (action) in
// do your stuff
}
let Cancel = UIAlertAction(
title: "Cancel", style: .default) { (action) in
// do your stuff
}
alert.addAction(Reset)
alert.addAction(Cancel)
present(alert, animated: true, completion: nil)
Objective-C
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:#"Basic Alert style"
message:#"Basic Alert With Buttons"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *Reset = [UIAlertAction
actionWithTitle:NSLocalizedString(#"Reset", #"Reset action")
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction *action)
{
NSLog(#"Reset action");
}];
UIAlertAction *Cancel = [UIAlertAction
actionWithTitle:NSLocalizedString(#"Cancel", #"Cancel action")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(#"Cancel action");
}];
[alert addAction:Reset];
[alert addAction:Cancel];
[self presentViewController:alert animated:YES completion:nil];
output
for additional Information see this
only red Color is possible when you set UIAlertActionStyle.Destructive
Check this link
UIAlertController custom font, size, color

How to create alert, sliding from bottom with buttons on iOS?

How to create an alert like Instagram unfollow alert(two buttons, image and message) on iOS? Is there any ready component or should I develop it from scratch?
Here is a screenshot:
There is an implementation (UIAlertController), but without the image.
Here's a working example:
UIAlertController* deleteAlert = [UIAlertController alertControllerWithTitle:#"Unfollow?"
message:
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction* unfollowAction = [UIAlertAction actionWithTitle:#"Unfollow" style:UIAlertActionStyleDestructive
handler:^(UIAlertAction * action) {
//Code to unfollow
}];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(#"Cancel", nil) style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action) {
}];
[deleteAlert addAction:unfollowAction];
[deleteAlert addAction:cancelAction];
[self presentViewController:deleteAlert animated:YES completion:nil];
You can find more informations on how to add an image to a UIAlertController in this post:
Add Image to UIAlertAction in UIAlertController
Swift 4 version
let deleteAlert = UIAlertController(title: "Unfollow", message: "", preferredStyle: UIAlertController.Style.actionSheet)
let unfollowAction = UIAlertAction(title: "Unfollow", style: .destructive) { (action: UIAlertAction) in
// Code to unfollow
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
deleteAlert.addAction(unfollowAction)
deleteAlert.addAction(cancelAction)
self.present(deleteAlert, animated: true, completion: nil)

How to add text input in alertview of ios 8?

I want to add text input in alert-view of ios 8.
I know it was done using UIAlertController but not have any idea.
How to do it ?
Screenshot
Code
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: #"Login"
message: #"Input username and password"
preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = #"name";
textField.textColor = [UIColor blueColor];
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.borderStyle = UITextBorderStyleRoundedRect;
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = #"password";
textField.textColor = [UIColor blueColor];
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.secureTextEntry = YES;
}];
[alertController addAction:[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSArray * textfields = alertController.textFields;
UITextField * namefield = textfields[0];
UITextField * passwordfiled = textfields[1];
NSLog(#"%#:%#",namefield.text,passwordfiled.text);
}]];
[self presentViewController:alertController animated:YES completion:nil];
AlertViewController
// use UIAlertController
UIAlertController *alert= [UIAlertController
alertControllerWithTitle:#"Title"
message:#"SubTitle"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
//Do Some action here
UITextField *textField = alert.textFields[0];
NSLog(#"text was %#", textField.text);
}];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
NSLog(#"cancel btn");
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = #"placeHolderText";
textField.keyboardType = UIKeyboardTypeDefault;
}];
[self presentViewController:alert animated:YES completion:nil];
UIAlertView
UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:#"Title"
message:#"SubTitle"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
dialog.alertViewStyle = UIAlertViewStylePlainTextInput;
[dialog show];
}
Example of implementation with Swift 3:
var textField: UITextField?
// create alertController
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
alertController.addTextField { (pTextField) in
pTextField.placeholder = "usefull placeholdr"
pTextField.clearButtonMode = .whileEditing
pTextField.borderStyle = .none
textField = pTextField
}
// create cancel button
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (pAction) in
alertController.dismiss(animated: true, completion: nil)
}))
// create Ok button
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (pAction) in
// when user taps OK, you get your value here
let inputValue = textField?.text
alertController.dismiss(animated: true, completion: nil)
}))
// show alert controller
self.present(alertController, animated: true, completion: nil)
UIAlertView *myView = [[UIAlertView alloc]initWithTitle:#"Input" message:#"Enter your value" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
myView.alertViewStyle = UIAlertViewStylePlainTextInput;
[myView textFieldAtIndex:0].delegate = self;
[myView show];
you can cover this way .Thanks
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Title" message:#"Please enter someth" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
av.alertViewStyle = UIAlertViewStylePlainTextInput;
[av textFieldAtIndex:0].delegate = self;
[av show];
also, you will need to implement UITextFieldDelegate, UIAlertViewDelegate protocols.
and if you user uialertcontroller then use this one
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"My Title"
message:#"Enter User Credentials"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Do Some action here
}];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:ok];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = #"Username";
}];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = #"Password";
textField.secureTextEntry = YES;
}];
[self presentViewController:alert animated:YES completion:nil];
Here's handy method with submit/cancel and completion handler for text if inputted:
/**
Presents an alert controller with a single text field for user input
- parameters:
- title: Alert title
- message: Alert message
- placeholder: Placeholder for textfield
- completion: Returned user input
*/
func showSubmitTextFieldAlert(title: String,
message: String,
placeholder: String,
completion: #escaping (_ userInput: String?) -> Void) {
let alertController = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.placeholder = placeholder
textField.clearButtonMode = .whileEditing
}
let submitAction = UIAlertAction(title: "Submit", style: .default) { (action) in
let userInput = alertController.textFields?.first?.text
completion(userInput)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
completion(nil)
}
alertController.addAction(submitAction)
alertController.addAction(cancelAction)
present(alertController, animated: true)
}
This one is work for me:
let passwordString = lableGetPassword.text
var textField: UITextField?
// create alertController
let alertController = UIAlertController(title: "Password", message: "Save the password. Give a tag name.", preferredStyle: .alert)
alertController.addTextField { (pTextField) in
pTextField.placeholder = "Tag Name"
pTextField.clearButtonMode = .whileEditing
pTextField.borderStyle = .none
textField = pTextField
}
// create cancel button
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (pAction) in
alertController.dismiss(animated: true, completion: nil)
}))
// create Ok button
alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: { [self] (pAction) in
// when user taps OK, you get your value here
let name = textField?.text
save(name: name!, password: passwordString!)
alertController.dismiss(animated: true, completion: nil)
}))
// show alert controller
self.present(alertController, animated: true, completion: nil)
UIAlertViewController with text input
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title"
message:nil
preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
// optionally configure the text field
textField.keyboardType = UIKeyboardTypeAlphabet;
}];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
UITextField *textField = [alert.textFields firstObject];
textField.placeholder = #"Enter Input";
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
func askForName() {
let alert = UIAlertController(title: "Enter Text",
message: "Enter some text below",
preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = "New Text"
}
let action = UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert!.textFields![0]
print("Text field: \(textField.text)")
})
alert.addAction(action)
present(alert, animated: true, completion: nil)
}

Resources